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

How to implement create or update using mongoose?

1个答案

1

In Mongoose, creating records is typically done by using the new keyword to create a new instance and then calling the instance's .save() method. For updating records, you can use the model's update methods, such as .updateOne(), .updateMany(), and .findOneAndUpdate().

Here are some basic examples for creating and updating records:

Creating Records

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; // Define a simple Schema const userSchema = new Schema({ name: String, age: Number }); // Create the model const User = mongoose.model('User', userSchema); // Create a new user instance const newUser = new User({ name: 'John Doe', age: 30 }); // Save the new user instance to the database newUser.save(function(err, user) { if (err) return console.error(err); console.log('User created:', user); });

Updating Records

You can use Model.updateOne, Model.updateMany, or Model.findOneAndUpdate to update records. Here are some simple examples:

updateOne

javascript
// Update a single document, matching the first record that meets the criteria User.updateOne({ name: 'John Doe' }, { age: 31 }, function(err, result) { if (err) return console.error(err); console.log('Result of updateOne:', result); });

updateMany

javascript
// Update multiple documents, matching all records that meet the criteria User.updateMany({ name: 'John Doe' }, { age: 31 }, function(err, result) { if (err) return console.error(err); console.log('Result of updateMany:', result); });

findOneAndUpdate

javascript
// Find a matching document, update it, and return the updated document User.findOneAndUpdate({ name: 'John Doe' }, { age: 31 }, { new: true }, function(err, user) { if (err) return console.error(err); console.log('Updated user:', user); });

In the above findOneAndUpdate example, the option { new: true } ensures that the updated document is returned instead of the original document. If you don't set this option, the original document is returned by default.

When performing update operations with Mongoose, you can also use database update operators such as $set and $inc to more precisely control the update behavior.

2024年6月29日 12:07 回复

你的答案