user5809117
user5809117

Reputation:

findOneAndUpdate() returns null in value on upsert

I'm new to mongodb and mongoose.

Please help me out! I'm stuck in this problem that I describe below.

I have this static method that I call from a controller(a router).

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

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

But, when I call this on the first time after the initial app launch, it returns null in value.

{ lastErrorObject: { updatedExisting: false, n: 0 },
  value: null,
  ok: 1 } // 1 means the execution succeeded 
          // in fact, i see the inserted data in mongo database.

According to this mongodb document, it shouldn't be null when upsert&new properties are true.

Because I get null in value property of the returned object, it leads to this error and crush my application.

TypeError: Cannot read property 'sequence' of null

But, after the second launch of application, when I call the same static method, it works fine without getting any errors.

Any idea how to solve this problem??

Upvotes: 13

Views: 13482

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311935

According to the 2.0 node.js native driver documentation, the option that controls whether findOneAndUpdate returns the original or new document is called returnOriginal, not new.

So your code would need to look like this instead:

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

But it would probably be better to do this directly in Mongoose by using Model.findOneAndUpdate where the option is named new:

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

The docs you link to are for findAndModify in the MongoDB shell, where the option is also named new. Very confusing.

Upvotes: 19

Related Questions