Update if exists, insert if it doesn’t exist – How to do Upsert in Mongoose?
To find a document and update it using Mongoose, you can use the findOneAndUpdate schema method. As the name implies, findOneAndUpdate() filter the document first that matches a given filter, applies an update, and returns the document. Roles.findOneAndUpdate({role:req.params.role},{modules: req.body.modules}); But what if the document that is to be updated doesn’t exist? You can insert it as a new document, … Read more