链接承诺更新Mongoose中的参考文档

时间:2017-01-25 09:27:40

标签: node.js mongodb mongoose promise

给出以下架构:

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

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

如何更新user.account以获取其引用字段account._owner的值。创建帐户文档时,我想查找并替换user.account值。我的路线看起来像这样:

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的值)

2 个答案:

答案 0 :(得分:2)

Mongoose处理承诺: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);
    });
});

答案 1 :(得分:1)

另一种解决方案是将挂钩附加到帐户模型的save操作

var Owner = require('path/to/owner/model');
var schema = new Schema({name:String,_owner:{type: Schema.Types.ObjectId,ref: 'owner'}}); // ref will be useful if you want to use populate later
schema.post('save', function(account) {
  return Owner.findOne({uid:account._owner})
      .then(owner => {
        owner.account = account._id; // assign account id to user
        return owner.save();
      })
});

然后你只需创建一个新的帐户对象,钩子就会在后台完成。

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

IMO,路线看起来更干净,你可以尝试一下。