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

How to update if exists otherwise insert new document

1个答案

1

Updating documents in Mongoose typically involves several methods, including Model.updateOne(), Model.updateMany(), and Model.findOneAndUpdate(). If you want to insert a new document when the document does not exist, you can use the Model.findOneAndUpdate() method with the upsert option. Here is an example:

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; const userSchema = new Schema({ username: String, email: String, // Other fields... }); const User = mongoose.model('User', userSchema);

Then, if you want to update a user's email, you can do the following:

javascript
// Assume we have a user ID and a new email address const userId = 'some-user-id'; const newEmail = 'newemail@example.com'; User.updateOne({ _id: userId }, { email: newEmail }, (err, result) => { if (err) { // Handle errors } else { // Update successful; result.nModified indicates how many documents were modified } });

If you want to create a new document when the document does not exist during the update, you can use the findOneAndUpdate() method with upsert: true, as shown below:

javascript
// Assume we have a username and an email address, and we want to update or create the user const username = 'johndoe'; const email = 'johndoe@example.com'; User.findOneAndUpdate( { username: username }, // Query condition { username: username, email: email }, // Data to update or insert { upsert: true, new: true }, // Options: upsert indicates insertion if not exists, new indicates returning the updated document (err, doc) => { if (err) { // Handle errors } else { // If the document exists, doc is the updated document; if not, doc is the newly created document } } );

In this example, the findOneAndUpdate method searches for a document with the username 'johndoe' and updates its email address. If no matching document is found, Mongoose creates a new document containing the provided username and email.

Note that when using upsert: true, Mongoose will default to creating a new document based on the query conditions. If your query conditions include fields outside the model definition (such as the username in the above example), you may need to ensure these fields exist in the model definition; otherwise, they may not be included in the newly created document. Additionally, since the upsert operation is atomic, you do not need to worry about other processes or threads inserting the same data between the query and insertion.

2024年6月29日 12:07 回复

你的答案