更新时间:2023-02-06 11:13:06
在您的代码中使用方法的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(){
...
});