Mongoose findOneAndUpdate Upsert _id null?

前端 未结 8 437
生来不讨喜
生来不讨喜 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:17

    I had this same problem and couldn't figure out a way to get it to work. I ended up writing my own upsert method like so....

    var upsert = function(model, data, f){
      if (!data._id) {
        model.create(data, f);
      } else {
        var id = data._id;
        delete data._id;
        model.findOneAndUpdate({_id: id}, data, f);
      }
    }
    

    That allows me to call it for any of my models with one line of code...

    upsert(Team, team, f);
    

    There might be a better way to do it, but this is working for me. I can do updates and inserts and I don't get a null _id on insert.

提交回复
热议问题