Mongoose findOneAndUpdate和upsert返回没有错误,没有文档受到影响 [英] Mongoose findOneAndUpdate and upsert returns no errs, no documents affected
问题描述
我有一个非常小的模型:
I have a very minimal model:
var CompanySchema = new mongoose.Schema({
name: { type: String, required: true, unique: true },
});
var Company = mongoose.model('Company', CompanySchema)
我试图添加单个文档,如果它不存在。目前,我测试时没有文档:
I am attempting to add a single document if it doesn't exist. Currently, there are no documents while I test:
models.Company.findOneAndUpdate({
name: 'companyName'
}, {upsert: true}, function(err, numberAffected, raw){
console.log(err, numberAffected, raw)
})
This is using the upsert
options from the Mongoose docs
然而错误
是 null
, numberAffected
为空。为什么我的文档没有更新?
However err
is null
, numberAffected
is null. Why isn't my document updated?
推荐答案
在您的代码中使用方法的3参数版本 findOneAndUpdate
所以,根据您发布的文档,参数是: A.findOneAndUpdate(条件,更新,回调)
。
in your code you are using the 3 parameter version of the method findOneAndUpdate
so, according to the documentation you posted, the parameters are: A.findOneAndUpdate(conditions, update, callback)
.
您应该使用方法的第4个参数版本来指定upsert选项。
You should use the 4th parameters version of the method to specify the upsert option.
我想指出的是我从未使用过框架猫鼬。希望这会有所帮助。
I would like to point out that I never used the framework mongoose. Hope this helps.
编辑:
是的,在您的情况下,条件
和 update
是一样的。如果您的对象比示例中显示的对象更复杂,您可能需要检查_id或唯一(不受MongoDB保证)属性(如果它有索引,则更好)。例如:
Yes, in your case, conditions
and update
are the same. If your object is more complex then the one showed in the example, you might want to check for the _id or a "unique" (not guaranteed by MongoDB) attribute (better if it has an index on it). For example:
var myObj = ...;
collection.findOneAndUpdate({uniqueAttr: myObj.uniqueAttr}, myObj, {upsert: true}, function(){
...
});
这篇关于Mongoose findOneAndUpdate和upsert返回没有错误,没有文档受到影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!