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

Mongoose 中如何更新文档?如何文档不存在则插入新文档?

5 个月前提问
3 个月前修改
浏览次数68

5个答案

1
2
3
4
5

在Mongoose中更新文档通常可以使用多种方法,这些方法包括 Model.updateOne(), Model.updateMany(), Model.findOneAndUpdate() 等。如果您想要在文档不存在的情况下插入新文档,可以使用 Model.findOneAndUpdate() 方法配合 upsert 选项。这里是一个例子:

首先,您需要一个模型来代表您的集合,例如:

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; const userSchema = new Schema({ username: String, email: String, // 其他字段... }); const User = mongoose.model('User', userSchema);

然后,如果您想更新一个用户的邮箱,可以这样做:

javascript
// 假设我们有一个用户ID和一个新的邮箱地址 const userId = 'some-user-id'; const newEmail = 'newemail@example.com'; User.updateOne({ _id: userId }, { email: newEmail }, (err, result) => { if (err) { // 处理错误 } else { // 更新成功,result.nModified 可以告诉你有多少文档被修改了 } });

如果您想要在更新时如果该文档不存在就创建一个新的文档,可以使用 findOneAndUpdate() 方法并设置 upsert: true,如下所示:

javascript
// 假设我们有一个用户名和一个邮箱地址,并希望更新或创建用户 const username = 'johndoe'; const email = 'johndoe@example.com'; User.findOneAndUpdate( { username: username }, // 查询条件 { username: username, email: email }, // 要更新或插入的数据 { upsert: true, new: true }, // 选项: upsert 表示如果不存在则插入,new 表示返回更新后的文档 (err, doc) => { if (err) { // 处理错误 } else { // 如果文档存在,则doc是更新后的文档;如果文档不存在,则doc是新创建的文档 } } );

在这个例子中,findOneAndUpdate 方法会查找一个用户名为 'johndoe' 的文档,并更新其邮箱地址。如果没有找到匹配的文档,Mongoose将创建一个新的文档,其中包含提供的用户名和邮箱。

请注意,当使用 upsert: true 时,Mongoose 会默认按查询条件创建一个新的文档。如果你的查询条件包含字段之外的模型定义(比如上面的例子中的 username),你可能需要确保这些字段在模型定义中存在,否则它们可能不会被包含在新创建的文档中。此外,由于 upsert 操作是原子的,所以不需要担心在查询和插入之间有其他进程或线程插入相同的数据。

2024年6月29日 12:07 回复

In Mongoose, you'd use Person.update per the documentation. In order to create a document if it doesn't already exist, you need to pass { upsert : true } in the options hash as it defaults to false.

i.e.

shell
Person.update( { name : 'Ted' }, { name : 'Ted', age : 50 }, { upsert : true }, callback );
2024年6月29日 12:07 回复

collection.update with upsert:true. See also here.

2024年6月29日 12:07 回复

[db.collection.replaceOne(filter, replacement, options)] with upsert:true

E.g. from here:

shell
try { db.restaurant.replaceOne( { "name" : "Pizza Rat's Pizzaria" }, { "_id": 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 8 }, { upsert: true } ); } catch (e){ print(e); }
2024年6月29日 12:07 回复

For python:

shell
import pymongo client = pymongo.MongoClient("mongodb_address") db = client.db_name collection = db[collection_name] # update 'data' if 'name' exists otherwise insert new document collection.find_one_and_update({"name": some_name}, {"$set": {"data": some_data}}, upsert=True)
2024年6月29日 12:07 回复

你的答案