findOneAndUpdate()在upsert的值上返回null
我是新来的mongodb和mongoose。
请帮帮我! 我被困在我下面描述的这个问题。
我有这个静态方法,我从一个控制器(路由器)调用。
IDCounterSchema.statics.getNextID = function(collectionName, callback){ this.collection.findOneAndUpdate( {name: collectionName}, {$inc: {sequence:1}}, {new: true, upsert: true}, callback ); };
但是,当我在初次应用程序启动后第一次调用此函数时,它将返回null值。
{ lastErrorObject: { updatedExisting: false, n: 0 }, value: null, ok: 1 } // 1 means the execution succeeded // in fact, i see the inserted data in mongo database.
根据这个mongodb文件 ,当upsert&new属性为true时,它不应该为null。
因为我返回的对象的值属性为null,它导致这个错误和粉碎我的应用程序。
TypeError: Cannot read property 'sequence' of null
但是,第二次启动应用程序后,当我调用相同的静态方法,它没有任何错误,它工作正常。
任何想法如何解决这个问题?
根据2.0 node.js本地驱动程序文档 ,控制findOneAndUpdate
返回原始文件还是新文档的选项称为returnOriginal
,不是new
。
所以你的代码需要看起来像这样:
this.collection.findOneAndUpdate( {name: collectionName}, {$inc: {sequence:1}}, {returnOriginal: false, upsert: true}, callback );
但是在Mongoose中直接使用Model.findOneAndUpdate
其中的选项名为new
可能会更好:
this.findOneAndUpdate( {name: collectionName}, {$inc: {sequence:1}}, {new: true, upsert: true}, callback );
您链接到的文档是在MongoDB shell中的findAndModify
,其中该选项也被命名为new
。 很混乱。