简体   繁体   中英

How to Update document which is returned as Output in mongodb find using mongoose

I first want to query for latest document in mongoose. Then, I want to update my document based on some condition, if Timestamp field is older 15 minutes, I want to create new instance and pass req.body , otherwise, I only want to update my query result with req.body ...

I have written own schema method tsFromID() to check if Timestamp is older 15 minutes, but I don't know how to update a returned result from a mongoose query:

exports.updateFlexPotenzial15minData = function(req, res, next) {
  const minID = +req.params.demo_id * 1000000;
  const maxID = (+req.params.demo_id + 1) * 1000000;
  FlexPotenzial.find({
    _id: {
      $gte: minID,
      $lt: maxID
    }
  }).sort({
    'createdAt': -1
  }).limit(1).exec(function(error, result) {
    if (error) {
      console.log(error);
    } else if (result.tsFromID()) {
      var newFP = new FlexPotenzial(req.body);
      newFP.save(function(err) {
        if (err) {
          console.log(err);
          res.status(400);
          res.send(err);
        } else {
          res.status(200);
          res.json({
            message: 'Neues Flexpotenzial erzeugt, da älter als 15 min!'
          });
        }
      });
    } else {
      result.update(update with req.body) < --How to update my returned result ?

    }    
  })
} 

If it's not possible to update a returned document instance , how would I do it otherwise?

You can use mongoose update query like this

...
...
else {
  FlexPotenzial.findByIdAndUpdate(result._id, req.body, (err, result) => {
    // do whatever you want
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM