Mongoose findOneAndUpdate Upsert _id null?

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

    Since we can now add default properties while destructuring objects in JavaScript, in the case that we are checking to see if a document exists, I find this the easiest way to either query via an existing _id or create a new one in the same operation, avoiding the null id problem:

    // someController.js using a POST route

    async function someController(req, res) {
      try {
      const {
        // the default property will only be used if the _id doesn't exist
        _id: new mongoose.Types.ObjectId(),
        otherProp,
        anotherProp
      } = req.body;
      const createdOrUpdatedDoc = await SomeModel.findOneAndUpdate(
        {
          _id
        },
        {
          otherProp,
          anotherProp
        },
        {
          new: true,
          upsert: true
        }
      ).exec();
      return res.json(201).json(createdOrUpdatedDoc);
      } catch (error) {
        return res.json(400).send({
          error,
          message: "Could not do this"
        })
      }
    }
    

提交回复
热议问题