nodejs mongoDB findOneAndUpdate(); 即使在数据库更新后也会返回true

我正在研究Ionic-1 + nodejs +angular度应用程序。 即使第一次调用更新数据库,我的mongoDb findOneAndUpdate()函数在每次调用时都会返回true。 的NodeJS:

 app.post('/booking', function (req, res) { var collection = req.db.get('restaurant'); var id = req.body.id; var status = req.body.status; collection.findOneAndUpdate({status: status, id: id},{$set:{status:"booked"}}, function (e, doc) { console.log(id, status); if (e) { console.log(e); } else if(!doc) { res.send(false); } else { res.send(true); } }); }); 

controller.js

 $scope.bookMe = function(id){ var Obj = {status: "yes", id: id}; myService.booking(Obj).success(function(res){ console.log(Obj, "Checking status") console.log(res); if (res == true) { var alertPopup = $ionicPopup.alert({ title: 'Booking Confirm', template: 'Thanks For Booking' }); } else{ var alertPopup = $ionicPopup.alert({ title: 'Error', template: ' Not available' }); } }) }; 

我在哪里做错了。 我的数据库得到更新,但它总是在下次调用时返回true。

有关findOneAndUpdate的文档说:

find一个匹配的文档,根据更新arg进行更新,传递任何选项,并将find的文档(如果有的话)返回给callback。 如果callback通过,查询立即执行。

所以这是正常的行为,你有一个doc

注意:

  1. 由于您正在检查可用性status="yes" ,更好的硬代码,而不是从请求查询/数据中获取。
  2. 根据您的要求更改响应res.send(true)/ res.send(false)

以下代码将工作

 app.post('/booking', function (req, res) { var collection = req.db.get('restaurant'); collection.findOneAndUpdate({ status: "yes", _id: req.body.id }, { $set: { status: "booked" } }, function (err, result) { //Error handling if (err) { return res.status(500).send('Something broke!'); } //Send response based on the required if (result.hasOwnProperty("value") && result.value !== null) { res.send(true); } else { res.send(false); } }); });