Topic 50 of 55
Mongoose CRUD
Overview
Once you have a Mongoose Model, you use it to perform Create, Read, Update, and Delete (CRUD) operations on your MongoDB database. Mongoose makes these operations simple using Promises.
Syntax
javascript
// Assuming 'User' is an imported Mongoose model
// CREATE
const newUser = await User.create({ name: 'Alice', age: 25 });
// OR: const user = new User({...}); await user.save();
// READ (Querying)
const allUsers = await User.find(); // Returns an array
const oneUser = await User.findOne({ name: 'Alice' }); // Returns an object
const userById = await User.findById('60c72b2f9b1e8a0015c9a1b2');
// UPDATE
// Updates multiple documents
await User.updateMany({ age: { $lt: 18 } }, { status: 'minor' });
// Finds one, updates it, and returns the NEW updated document
const updated = await User.findByIdAndUpdate(
'60c72b2...',
{ age: 26 },
{ new: true }
);
// DELETE
await User.findByIdAndDelete('60c72b2...');
await User.deleteMany({ status: 'banned' });Common Pitfalls
- Methods like `findByIdAndUpdate` bypass Mongoose validation by default! To enforce your schema rules during updates, you must pass `{ runValidators: true }` in the options object.
- Queries without `.exec()` still return a Promise-like object (a 'Thenable'), but using `.exec()` provides better stack traces if an error occurs.
Real-World Example
Advanced querying with pagination, sorting, and projection:
example
javascript
async function getActiveUsers() {
const users = await User
.find({ isActive: true }) // The filter criteria
.select('username email -_id') // Projection: Include username, email. EXCLUDE _id
.sort({ createdAt: -1 }) // Sort by newest first (-1)
.limit(10) // Only get 10 results
.skip(20) // Skip the first 20 (for page 3 pagination)
.exec(); // Explicitly executes the query and returns a Promise
return users;
}