如何使用 mongoose 和 bluebird promise 确认更新是否成功

How to confirm if update succeeds using mongoose and bluebird promise

我正在使用 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);
    }
})

mongoose return 更新后是否显示成功消息?我无法从更新查询 return 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);
   })

我假设你在这里使用 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);
       })

Mongoose 文档说

Mongoose async operations, like .save() and queries, return Promises/A+ conformant promises. This means that you can do things like MyModel.findOne({}).then() and yield MyModel.findOne({}).exec() (if you're using co).

还有 Mongoose Update returns 更新后的文档。

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

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