Understand Mongoose Models and Documents
A Mongoose model is created from a schema and provides an interface for interacting with a MongoDB collection.
For example:
const user = await User.findOne({ email: 'john@example.com' });
Here:
- User is the Mongoose model.
- findOne() is a model query method.
- The result is a Mongoose document or null.
A Mongoose document represents an individual database record and provides methods such as save() and toObject().
Models are also used for creating, updating, and deleting documents.
Create a User Document
const user = new User({
name: 'John Doe',
email: 'john@example.com',
password: 'hashed-password'
});
await user.save();
console.log(user._id);Creates a Mongoose document and persists it to MongoDB using save(). The password value is illustrative; real registration must hash passwords before saving.
Key Takeaways
Models provide database operations.
Documents represent individual records.
save() persists a new or modified document.