Update model with Mongoose, Express, NodeJS

后端 未结 5 2038
一向
一向 2020-12-23 22:15

I\'m trying to update an instantiated model (\'Place\' - I know it works from other routes) in a MongoDB and have spent a while trying to properly do so. I\'m also trying t

5条回答
  •  囚心锁ツ
    2020-12-23 22:32

    You have to find the document before updating anything:

    Place.findById(req.params.id, function(err, p) {
      if (!p)
        return next(new Error('Could not load Document'));
      else {
        // do your updates here
        p.modified = new Date();
    
        p.save(function(err) {
          if (err)
            console.log('error')
          else
            console.log('success')
        });
      }
    });
    

    works for me in production code using the same setup you have. Instead of findById you can use any other find method provided by mongoose. Just make sure you fetch the document before updating it.

提交回复
热议问题