我有一个非常简单的模型:

var CompanySchema = new mongoose.Schema({
    name: { type: String, required: true, unique: true },
});

var Company = mongoose.model('Company', CompanySchema)

我正在try 添加一个不存在的文档.目前,我测试时没有文档:

models.Company.findOneAndUpdate({
    name: 'companyName'
}, {upsert: true}, function(err, numberAffected, raw){
    console.log(err, numberAffected, raw)
})

这是使用upsert options from the Mongoose docs

然而,errnullnumberAffected是空的.为什么我的文档没有更新?

推荐答案

在您的代码中,您使用的是方法findOneAndUpdate的3参数版本,因此,根据您发布的文档,参数是:A.findOneAndUpdate(conditions, update, callback).

您应该使用该方法的第四个参数版本来指定upsert选项.

我想指出,我从未使用过框架mongoose.希望这有帮助.

编辑:

var myObj = ...;
collection.findOneAndUpdate({uniqueAttr: myObj.uniqueAttr}, myObj, {upsert: true}, function(){
     ...
});

Mongodb相关问答推荐

通过mongoDB中的查找从管道中删除被阻止的用户

在一个视图中连接两个集合MongoDB;展开有什么作用?

在MongoDB中是否可以按递增顺序更新多个文档?

GO:如何在MongoDB中区分空字符串和nil

如何使用ID数组对一个集合中的金额求和并更新另一个集合中的字段?

MongoDB MQL,将列表一分为二,仅获取唯一值

Mongo $sort然后$group,顺序能保证吗?

无法通过管理邮箱/密码身份验证注册/登录新用户帐户(类型错误:加载失败)

mongoDB文档数组字段中的唯一项如何

如何使用 Golang 库获取 MongoDB 版本?

子文档上的mongoose唯一索引

如何使用 Spring Data MongoDB 通过 GridFS ObjectId 获取二进制流

MongoDB 聚合 $divide 计算字段

在 mongodb 的一次更新调用中推送到两个单独的数组

如何在mongodb中删除数组的第n个元素

当前的 URL 字符串解析器已弃用

show dbs 给出Not Authorized to execute command错误

使用 C# 聚合 $lookup

Mongoose 为所有嵌套对象添加 _id

对象不是 JSON 可序列化的