Topic 49 of 55
Mongoose Schema & Model Creation
Overview
MongoDB is a NoSQL database, meaning it doesn't enforce structure. Mongoose is an Object Data Modeling (ODM) library for Node.js that adds strict schemas, validation, and relation mapping to MongoDB, ensuring your data is predictable.
Syntax
javascript
const mongoose = require('mongoose');
// 1. Connect to the database
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Connection failed', err));
// 2. Define a Schema (the blueprint)
const userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true },
age: { type: Number, min: 18, default: 18 },
createdAt: { type: Date, default: Date.now }
});
// 3. Create a Model (the compiled class based on the schema)
// 'User' will become the collection 'users' in MongoDB
const User = mongoose.model('User', userSchema);
module.exports = User;Common Pitfalls
- Arrow functions `() => {}` should NOT be used for Mongoose instance methods or virtuals because they lexical bind `this`, preventing you from accessing the document's properties. Always use `function() {}`.
- Setting `unique: true` is not a validator; it tells MongoDB to build an index. If you add it to an existing collection with duplicates, it will silently fail to build the index.
Real-World Example
Adding custom methods and virtual properties to a Schema:
example
javascript
const personSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
// Virtual Property: Doesn't exist in DB, computed on the fly
personSchema.virtual('fullName').get(function() {
return `${this.firstName} ${this.lastName}`;
});
// Custom Instance Method
personSchema.methods.sayHello = function() {
console.log(`Hi, my name is ${this.firstName}`);
};
const Person = mongoose.model('Person', personSchema);
// Usage:
const p = new Person({ firstName: "John", lastName: "Doe" });
console.log(p.fullName); // "John Doe"
p.sayHello(); // "Hi, my name is John"