使用Mongoose承诺find并更新

我正在尝试使用Mongoose Promises来获得更清晰的代码(请参阅嵌套函数)。 具体来说,我试图build立这样的事情:

Model.findOne({_id: req.params.id, client: req.credentials.clientId}).exec() .then(function(resource){ if (!resource) { throw new restify.ResourceNotFoundError(); } return resource; }) .then(function(resource) { resource.name = req.body.name; return resource.save; <-- not correct! }) .then(null, function(err) { //handle errors here }); 

所以,在其中的一个承诺,我将需要保存我的模型。 从最新的稳定版本开始,Model.save()不会返回一个promise(bug在这里 )。

要使用经典的保存方法,我可以使用这个:

  //..before as above .then(function(resource) { resource.name = req.body.name; resource.save(function(err) { if (err) throw new Error(); //how do I return OK to the parent promise? }); }) 

但是,如同在代码中所评论的那样,我如何返回保存callback的savecallback(运行asynchronous)的返回值呢?

有没有更好的办法?

(顺便说一句,findOneAndUpdate是我的情况下不去的解决scheme)

这样做的一种方法是将.save代码包装在你自己的方法中,它返回一个承诺。 你需要一个承诺库,如RSVP或Q.我会写在RSVP,但你应该明白了。

 var save = function(resource) { return new RSVP.Promise(function(resolve, reject) { resource.save(function(err, resource) { if (err) return reject(err); resolve(resource); }); }); } 

然后在你的调用代码中:

 // ... .then(function(resource) { resource.name = req.body.name; return save(resource); }) .then(function(resource) { // Whatever }) .catch(function(err) { // handle errors here }); 

另一种方法是节点化保存方法,但是我会按照上面详细描述的方式来完成。