findOneAndUpdate()在upsert中返回null值

7 mongoose mongodb node.js

我是mongodb和mongoose的新手.

请帮帮我!我陷入了下面我描述的这个问题.

我有一个静态方法,我从控制器(路由器)调用.

IDCounterSchema.statics.getNextID = function(collectionName, callback){

    this.collection.findOneAndUpdate(
        {name: collectionName},
        {$inc: {sequence:1}},
        {new: true, upsert: true},
        callback
    );
};
Run Code Online (Sandbox Code Playgroud)

但是,当我在初始应用程序启动后第一次调用它时,它会返回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.
Run Code Online (Sandbox Code Playgroud)

根据这个mongodb文档,当upsert和new属性为true时,它不应该为null.

因为我在返回的对象的value属性中得到null,它会导致此错误并粉碎我的应用程序.

TypeError: Cannot read property 'sequence' of null
Run Code Online (Sandbox Code Playgroud)

但是,在第二次启动应用程序之后,当我调用相同的静态方法时,它可以正常工作而不会出现任何错误.

任何想法如何解决这个问题?

Joh*_*yHK 9

根据2.0 node.js本机驱动程序文档,控制是否findOneAndUpdate返回原始文档或新文档的选项returnOriginal不会被调用new.

所以你的代码需要看起来像这样:

this.collection.findOneAndUpdate(
    {name: collectionName},
    {$inc: {sequence:1}},
    {returnOriginal: false, upsert: true},
    callback
);
Run Code Online (Sandbox Code Playgroud)

但它可能会更好地在猫鼬通过直接做到这一点Model.findOneAndUpdate,其中的选项命名为new:

this.findOneAndUpdate(
    {name: collectionName},
    {$inc: {sequence:1}},
    {new: true, upsert: true},
    callback
);
Run Code Online (Sandbox Code Playgroud)

您链接到的文档适用findAndModify于MongoDB shell,其中该选项也被命名new.很混乱.

  • 两个代码都有效!没注意到在执行第一个代码和第二个代码时返回对象的结构是不同的,所以我需要做一些工作才能使第二个代码工作。 (2认同)