How to Create Schema in Mongoose: Simple Guide
To create a schema in Mongoose, use
mongoose.Schema to define the structure of your documents by specifying fields and their types. Then, create a model with mongoose.model to interact with the database using that schema.Syntax
The basic syntax to create a schema in Mongoose involves using mongoose.Schema to define the fields and their types. Then, you create a model from the schema using mongoose.model. The model lets you create, read, update, and delete documents in MongoDB.
- mongoose.Schema: Defines the shape of the documents.
- new Schema({}): Pass an object with field names and types.
- mongoose.model(name, schema): Creates a model with a name and schema.
javascript
const mongoose = require('mongoose'); const schema = new mongoose.Schema({ fieldName: FieldType, anotherField: AnotherType }); const ModelName = mongoose.model('ModelName', schema);
Example
This example shows how to create a simple User schema with fields for name and age. Then it creates a model to use this schema.
javascript
const mongoose = require('mongoose'); // Define the User schema const userSchema = new mongoose.Schema({ name: String, age: Number }); // Create the User model const User = mongoose.model('User', userSchema); // Example usage: create a new user instance const newUser = new User({ name: 'Alice', age: 30 }); console.log(newUser);
Output
User { _id: new ObjectId("..."), name: 'Alice', age: 30 }
Common Pitfalls
Common mistakes when creating schemas in Mongoose include:
- Not using
new mongoose.Schema()and trying to assign a plain object. - Forgetting to create a model with
mongoose.model(). - Using incorrect field types or misspelling field names.
- Not connecting to MongoDB before using models.
Always define the schema with new mongoose.Schema() and then create a model to interact with the database.
javascript
/* Wrong way: missing 'new' keyword */ const wrongSchema = mongoose.Schema({ name: String }); // This may cause issues /* Right way: use 'new' keyword */ const rightSchema = new mongoose.Schema({ name: String });
Quick Reference
| Step | Code | Description |
|---|---|---|
| 1 | const schema = new mongoose.Schema({ field: Type }); | Define schema with fields and types |
| 2 | const Model = mongoose.model('ModelName', schema); | Create model from schema |
| 3 | const doc = new Model({ field: value }); | Create document instance |
| 4 | await doc.save(); | Save document to database |
Key Takeaways
Use new mongoose.Schema() to define the document structure clearly.
Create a model with mongoose.model() to work with the schema.
Always specify field types like String, Number, Date, etc.
Avoid skipping the 'new' keyword when creating schemas.
Connect to MongoDB before using models to avoid errors.