我是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.
根据this mongodb document,在upsert和new properties为true时,value不应为null。
因为我在返回对象的value属性中得到了null,导致了这个错误并且使我的应用程序崩溃。
TypeError: Cannot read property 'sequence' of null
但是,在第二次启动应用程序后,当我调用相同的静态方法时,它可以正常工作而不会出现任何错误。
有什么办法可以解决这个问题吗?