Mongoose findOneAndUpdate Upsert _id null?

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

    Try setting the upsert parameter to true in your call to update. From the mongoid docs: http://docs.mongodb.org/manual/reference/method/db.collection.update/#update-parameter

    Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found.

    0 讨论(0)
  • 2021-01-01 13:28

    This could be useful (from the docs):

    If you specify an _id field in either the query parameter or replacement document, MongoDB uses that _id field in the inserted document.

    So when you write:

    model.findOneAndUpdate({_id: id}, data, f);
    

    And id is null, it will insert a document with null as id.

    0 讨论(0)
提交回复
热议问题