0

I want to update a returned document from a find query, but even though I don't get any errors with the code below it doesn't work as intended:

var projectId = req.params.projectId
var object = req.body
var updatedProject = sanitizeProjectObject(object)

Project.findOne({project_id: projectId}, function(err, project) {
    if(err)
        next(err)

    if(!project)
        next(new Error(404, "Couldn't find a project with this id"))

    if(!isAllowedToEditProject(req, project))
        next(new Error(403, "You are not allowed to edit this project"))

    project.update({ $set: updatedProject }, function(err, resultProject) {
        logger.info(resultProject)
    })
})

Output is:

3:32:07 AM - info: ok=0, n=0, nModified=0

The updatedProject object contains 5 of the document's 8 fields which have changed. I can confirm that the values for these fields in "updatedProject" are different than the stored values.

So how can I update a returned document from the database using mongoose?

kentor
  • 16,553
  • 20
  • 86
  • 144
  • You are doing it all wrong use `.findOneAndUpdate({project_id: projectId},{ "$set": updatedProject }. { "new": true }, function(err,result) {` instead. And really you should be diffing the keys and only send the modfied elements to `$set` or other appropriate operators. – Neil Lunn Jun 05 '17 at 01:55
  • @NeilLunn okay I read about findOneAndUpdate but I thought I could use the returned instance instead. Can you explain why I should only send the modified elements instead of all? – kentor Jun 05 '17 at 01:59
  • 1
    No. `.update()` like `.findOneAndUpdate()` are methods of the "Model" and not the "instance". The instance has `.save()`. As for "why?", I already did that years ago. [Mongoose difference between .save() and using update()](https://stackoverflow.com/questions/22278761/mongoose-difference-between-save-and-using-update) – Neil Lunn Jun 05 '17 at 02:02
  • Hm I read it but in my case I could do the "client side update" anyways since I already got the instance to perform other checks. I assume I should simply use save() then or would you discourage me from doing so? – kentor Jun 05 '17 at 02:08
  • IMHO It's bad practice, but if you are relying on coded validations then the damage is already done. Just don't do what you are currently doing since `.update()` cannot be applied here. – Neil Lunn Jun 05 '17 at 02:15

0 Answers0