Constructing Documents in Mongoose
In Mongoose, documents are instances of models and represent individual records in your MongoDB collections. Constructing documents involves creating instances of a model, initializing them with data, and optionally saving them to the database.
Creating a Document Instance
To construct a new document, use the new
keyword with your compiled model:
const user = new User({
name: { first: 'Jane', last: 'Doe' },
email: 'jane.doe@example.com',
age: 28
});
Setting and Modifying Properties
You can set properties directly via the constructor or modify the instance properties later:
// Initial properties at construction time
const post = new Post({ title: 'Hello World', content: 'My first post' });
// Modifying properties after construction
post.title = 'Updated Title';
post.content = 'Updated content';
Saving Documents to MongoDB
To persist your constructed document to the database, call the asynchronous save()
method:
user.save()
.then(doc => console.log('Document saved:', doc))
.catch(err => console.error('Save error:', err));
Using Document Methods and Virtuals
Documents can use instance methods and virtual properties defined on the schema. This enables custom behavior and computed values.
user.fullName(); // Example instance method
console.log(user.fullName); // Example virtual property
Summary Table
Operation | Description | Code Example |
---|---|---|
Create | Initialize a new document instance | new Model(data) |
Modify | Update document properties | doc.property = value |
Save | Persist document to MongoDB | doc.save() |
Best Practices
- Validate data before saving documents.
- Use schema methods and virtuals to encapsulate logic.
- Handle errors during save operations gracefully.
- Create documents using model constructors consistently.
Conclusion
Constructing documents through Mongoose models provides a powerful and flexible way to manage MongoDB records. With support for instance methods and schema validations, your documents stay consistent and your data layer clean.
Comments
Post a Comment