How to Create a Model in Mongoose: Simple Guide
To create a model in Mongoose, first define a
Schema that describes the structure of your documents. Then use mongoose.model() with a name and the schema to create the model, which you can use to interact with your MongoDB collection.Syntax
Creating a model in Mongoose involves two main steps:
- Define a Schema: This sets the shape of the documents in the collection.
- Create the Model: This binds the schema to a collection and provides an interface to work with the data.
javascript
const mongoose = require('mongoose'); const schemaName = new mongoose.Schema({ field1: String, field2: Number, // more fields }); const ModelName = mongoose.model('ModelName', schemaName);
Example
This example shows how to create a simple User model with name and age fields, then create and save a user document.
javascript
const mongoose = require('mongoose'); // Connect to MongoDB (replace with your connection string) mongoose.connect('mongodb://localhost:27017/testdb', { useNewUrlParser: true, useUnifiedTopology: true }); // Define schema const userSchema = new mongoose.Schema({ name: String, age: Number }); // Create model const User = mongoose.model('User', userSchema); // Create a new user instance const newUser = new User({ name: 'Alice', age: 30 }); // Save to database newUser.save() .then(doc => { console.log('User saved:', doc); mongoose.connection.close(); }) .catch(err => { console.error('Error saving user:', err); mongoose.connection.close(); });
Output
User saved: { _id: <ObjectId>, name: 'Alice', age: 30, __v: 0 }
Common Pitfalls
Common mistakes when creating models in Mongoose include:
- Not defining a schema before creating a model.
- Using the same model name multiple times, which causes errors.
- Forgetting to connect to MongoDB before using models.
- Not handling asynchronous operations like
save()properly.
javascript
/* Wrong: Creating model without schema */ // const User = mongoose.model('User'); // This will cause an error /* Right: Always define schema first */ const userSchema = new mongoose.Schema({ name: String }); const User = mongoose.model('User', userSchema);
Quick Reference
| Step | Description | Code Example |
|---|---|---|
| 1 | Import Mongoose | const mongoose = require('mongoose'); |
| 2 | Define Schema | const schema = new mongoose.Schema({ field: String }); |
| 3 | Create Model | const Model = mongoose.model('Name', schema); |
| 4 | Use Model | const doc = new Model({ field: value }); doc.save(); |
Key Takeaways
Always define a schema before creating a Mongoose model.
Use mongoose.model() with a model name and schema to create the model.
Connect to MongoDB before using models to avoid connection errors.
Handle asynchronous operations like save() with promises or async/await.
Avoid reusing the same model name multiple times in your code.