乐闻世界logo
搜索文章和话题

What are the common CRUD operation methods in Mongoose Model?

2月22日 20:12

Mongoose Model is a constructor compiled from Schema, used to create and manipulate MongoDB documents. Model instances represent documents in the database and provide rich CRUD operation methods.

Creating Model

javascript
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, email: String, age: Number }); // Create Model, first parameter is collection name (automatically converted to plural) const User = mongoose.model('User', userSchema);

Main Model Methods

Creating Documents

javascript
// Method 1: Using new keyword const user = new User({ name: 'John', email: 'john@example.com' }); await user.save(); // Method 2: Using create method const user = await User.create({ name: 'John', email: 'john@example.com' }); // Method 3: Using insertMany const users = await User.insertMany([ { name: 'John', email: 'john@example.com' }, { name: 'Jane', email: 'jane@example.com' } ]);

Querying Documents

javascript
// Find all const users = await User.find(); // Conditional query const user = await User.findOne({ email: 'john@example.com' }); const users = await User.find({ age: { $gte: 18 } }); // Find by ID const user = await User.findById('507f1f77bcf86cd799439011'); // Chained query const users = await User.find({ age: { $gte: 18 } }) .select('name email') .sort({ name: 1 }) .limit(10);

Updating Documents

javascript
// Update single document const user = await User.findByIdAndUpdate( '507f1f77bcf86cd799439011', { age: 25 }, { new: true } // Return updated document ); // Conditional update const result = await User.updateOne( { email: 'john@example.com' }, { age: 25 } ); // Batch update const result = await User.updateMany( { age: { $lt: 18 } }, { status: 'minor' } ); // findOneAndUpdate const user = await User.findOneAndUpdate( { email: 'john@example.com' }, { age: 25 }, { new: true } );

Deleting Documents

javascript
// Delete by ID const user = await User.findByIdAndDelete('507f1f77bcf86cd799439011'); // Conditional delete const result = await User.deleteOne({ email: 'john@example.com' }); // Batch delete const result = await User.deleteMany({ age: { $lt: 18 } }); // findOneAndDelete const user = await User.findOneAndDelete({ email: 'john@example.com' });

Counting Documents

javascript
const count = await User.countDocuments({ age: { $gte: 18 } }); const count = await User.estimatedDocumentCount(); // Fast estimation

Model Static Methods

You can add custom static methods to Schema:

javascript
userSchema.statics.findByEmail = function(email) { return this.findOne({ email }); }; const User = mongoose.model('User', userSchema); const user = await User.findByEmail('john@example.com');
标签:Mongoose