【问题标题】:How to confirm if update succeeds using mongoose and bluebird promise如何使用 mongoose 和 bluebird promise 确认更新是否成功
【发布时间】:2015-04-01 20:20:57
【问题描述】:

我将bluebirdmongoose 用于节点页面。 我想在通过socket.js将数据发送回客户端之前检查更新是否成功。这是我无法弄清楚的代码部分:

.then(function(a) {
    var g = collection3.update({
        _id: a.one[0]._id
    }, {
        $set: {
            avg: a.one[0].avg
        }
    }).function(err, d) {
        if (!err) {
            return 1; // Here's the problem
        }
    }) return {
    updated: g,
    info: a
};
}).then(function(c) {
    console.log(c.updated); // I can't get the `1` value
    if (c == 1) {
        io.sockets.in('index|1').emit("estimate", c.three);
    }
})

猫鼬更新后是否返回成功消息?我无法从更新查询中返回 1 并将其传递给下一个 then 函数,而是得到了这个对象:

{ _mongooseOptions: {},
  mongooseCollection:
   { collection:
      { db: [Object],
        collectionName: 'table',
        internalHint: null,
        opts: {},
        slaveOk: false,
        serializeFunctions: false,
        raw: false,
        pkFactory: [Object],
        serverCapabilities: undefined },
     opts: { bufferCommands: true, capped: false },
     name: 'table',
     conn:....

这是完整的代码:

  socket.on("input",function(d){ 
    Promise.props({
       one: collection2.aggregate([
        {
         $match:{post_id:mongoose.Types.ObjectId(d.id)}
        },
        {
         $group:{
                 _id:"$post_id",
                 avg:{$avg:"$rating"}
                }
        }
       ]).exec();
   }).then(function(a){     
      var g = collection3.update({_id:a.one[0]._id},{$set:{avg:a.one[0].avg}}).function(err,d){
        if(!err){
          return 1; // Here's the problem
        }
      })
      return {updated:g,info:a};
   }).then(function(c){
      console.log(c.updated); // I can't get the `1` value
      if(c.updated == 1){
        io.sockets.in('index|1').emit("estimate",c.three);
      }
   }).catch(function (error) {
     console.log(error);
   })

【问题讨论】:

  • 如果您的承诺代码中有if (err),则说明出现了灾难性的错误——您能否重新评估整个部分?

标签: javascript node.js mongodb promise bluebird


【解决方案1】:

我假设你在这里使用 Mongoose,update() 是一个异步函数,你的代码是以同步方式编写的。

试试:

   socket.on("input",function(d){ 
        Promise.props({
           one: collection2.aggregate([
            {
             $match:{post_id:mongoose.Types.ObjectId(d.id)}
            },
            {
             $group:{
                     _id:"$post_id",
                     avg:{$avg:"$rating"}
                    }
            }
           ]).exec()
       }).then(function(a){     
          return collection3.update({_id:a.one[0]._id},{$set:{avg:a.one[0].avg}})
          .then(function(updatedDoc){
            // if update is successful, this function will execute

          }, function(err){
            // if an error occured, this function will execute

          })

       }).catch(function (error) {
         console.log(error);
       })

【讨论】:

    【解决方案2】:

    猫鼬文档说

    Mongoose 异步操作,如 .save() 和查询,返回 Promises/A+ 一致的承诺。这意味着你可以做一些事情 像 MyModel.findOne({}).then() 和 yield MyModel.findOne({}).exec() (如果你使用 co)。

    还有 Mongoose Update 返回更新后的文档。

    所以这应该看起来像这样。

    function runBarryRun(d) {
        Promise.props({
            one: aggregateCollection2(d)
        })
        .then(updateCollection3)
        .then(updatedDoc => {
            // if update is successful, do some magic here
            io.sockets.in('index|1').emit("estimate", updatedDoc.something);
        }, err => {
           // if update is unsuccessful, find out why, throw an error maybe
        }).catch(function(error) {
            // do something here
            console.log(error);
        });
    }
    
    function aggregateCollection2(d) {
        return collection2.aggregate([{
            $match: { post_id: mongoose.Types.ObjectId(d.id) }
        }, {
            $group: {
                _id: "$post_id",
                avg: { $avg: "$rating" }
            }
        }]).exec();
    }
    
    function updateCollection3(a) {
        return collection3.update({ _id: a.one[0]._id }, { $set: { avg: a.one[0].avg } }).exec();
    }
    
    socket.on("input", runBarryRun);
    

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 2020-03-14
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多