【问题标题】:nodejs mongoDB findOneAndUpdate(); returns true even after database is updatednodejs mongoDB findOneAndUpdate();即使在数据库更新后也返回 true
【发布时间】:2018-02-13 23:11:42
【问题描述】:

我正在开发一个 Ionic-1 + nodejs + angular 应用程序。即使第一次调用更新数据库,我的 mongoDb findOneAndUpdate() 函数也会在每次调用时返回 true。 节点:

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。

【问题讨论】:

标签: javascript angularjs node.js mongodb ionic-framework


【解决方案1】:

关于findOneAndUpdate 的文档说:

找到一个匹配的文档,根据更新参数更新它,传递任何选项,并将找到的文档(如果有的话)返回给回调。如果回调通过,查询会立即执行。

因此,您收到doc 是正常行为。

【讨论】:

  • 那么我应该使用哪个函数来更新和检查?
  • 我不明白你的问题。如果数据库中不存在数据,doc 为 false。如果数据存在,则update it 和doc 等于数据。 (如果您希望在数据不存在的情况下创建数据,请将 upsert 选项设置为 true)
  • 问题是如果用户预订餐厅数据库检查该餐厅的 ID 和状态,如果状态显示可用,则状态更新为已预订。但在我的情况下,如果另一个用户预订同一家餐厅,即使数据库已更新,它也会向他显示预订确认。
  • 你应该尝试console.logdoc,看看你发回给用户(res)的内容。它应该工作。我的猜测是,当您执行if (res == true) 时,res 被转换为布尔值并被转换为true,但实际上res.send(false) 被发送
  • console.log(doc);输出:{ lastErrorObject: { updatedExisting: false, n: 0 }, value: null, ok: 1 }
【解决方案2】:

注意:

  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);
        }
   });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 2018-07-10
    • 2014-12-23
    • 2019-10-14
    • 2019-04-19
    相关资源
    最近更新 更多