Mongoose findOneAndUpdate Upsert _id null?

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

    Thanks to JohnnyHK for a helpful answer above. I came up with a one-liner since it's used so frequently:

    query = args._id ? { _id: args._id } : { _id: new ObjectId() };
    

    It relies on the following require:

    const ObjectId = require('mongodb').ObjectID;
    

提交回复
热议问题