链接承诺将更新Mongoose中的参考文档 [英] Chaining promise to update a reference document in Mongoose

查看:60
本文介绍了链接承诺将更新Mongoose中的参考文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下架构:

user
  { uid:12345, name:myname, account=null }

account
  { _id:6789, name:"myaccount", _owner:12345 }

如何更新user.account以具有其引用的字段account._owner的值.创建帐户文档后,我想查找并替换user.account值.我的路线如下所示:

How can I update the user.account to have the value of its referenced field account._owner. When the account document is created I want to find and replace the user.account value. The route I have looks like this:

app.post('/accounts', authenticate, (req, res) => {
    var account = new Account({
        name: req.body.name,
        _owner: req.body._owner,
    });
    account.save().then((doc) => {
    //here i wasnt to update a refernce to a 
    // an account field in a User document and set 
    //it to the account.owner created above.
        res.send(doc);
    }, (e) => {
        res.status(400).send(e);
    });
});

在我的示例中,创建帐户时 我想将user.account更新为6789(创建的帐户ID的值)

In my example when the account is created I want to update user.account to 6789 (the value of the created account id)

推荐答案

猫鼬处理承诺: http://mongoosejs.com/docs/promises.html

所以您可以简单地:

app.post('/accounts', authenticate, (req, res) => {
    var account = new Account({
        name: req.body.name,
        _owner: req.body._owner,
    });
    account.save()
        .then((doc) => User.findOneAndUpdate(
            { uid: req.body._owner },
            { $set: { account: doc._id } },
            { new: true }
        )
        .then(() => doc);
    }).then((account) => {
        res.send(account);
    }, (e) => {
        res.status(400).send(e);
    });
});

这篇关于链接承诺将更新Mongoose中的参考文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆