如何确认更新是否成功使用mongoose和蓝鸟的承诺

我正在使用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会返回成功消息吗? 我不能从更新查询返回1 ,并将其传递给下一个函数,而是我得到这个对象:

 { _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()是一个asynchronous函数,你的代码是以同步风格写的。

尝试:

  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文档说

Mongooseasynchronous操作,如.save()和查询,返回Promises / A +符合的承诺。 这意味着您可以执行MyModel.findOne({}),then()和MyModel.findOne({})。exec()(如果使用的是co)。

此外Mongoose更新返回更新的文档。

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

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