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
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"
})
}
}