FindOneAndUpdate () returns null to upsert

I am new to mongodb and mongoose.

Please help me! I am stuck in this problem, which I will discuss below.

I have this static method that I call from the controller (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 the first time after the first launch of the application, it returns null to the 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 file , it should not be null if upsert & new properties are true.

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

TypeError: Cannot read property 'sequence' of null

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

Any idea how to solve this problem?

+4
1

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
);

, , findAndModify MongoDB, new. .

+4

Source: https://habr.com/ru/post/1626738/


All Articles