Mongoose findOneAndUpdate Upsert _id null?

前端 未结 8 461
生来不讨喜
生来不讨喜 2021-01-01 12:57

I\'d like to have a single method that either creates or updates a document for a policy. Searching and trying different techniques like this one, I have come up with a nul

8条回答
  •  梦谈多话
    2021-01-01 13:22

    I am not using Mongoose, but I run into similar issue with MongoDB. For Upsert action when new object was inserted the MongoDB was setting null to _id.

    I was calling:

    findOneAndUpdate({my_id:'my_unique_id'}, obj, {upsert: true})
    

    where obj._id was undefined.

    The problem was that _id was present on list of keys Object.keys(obj). I found that I was assigning obj._id = some_variable, where some_variable was undefined, and that was causing _id to appear on a list of keys.

    I applied workaround by calling right before upsert:

    if (_.isUndefined(obj._id)) {
      delete obj._id;
    }
    

提交回复
热议问题