javascript 如何填充()猫鼬 .findOneAndUpdate 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24024038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:01:08  来源:igfitidea点击:

how to populate() a mongoose .findOneAndUpdate object

javascriptmongoose

提问by Jorre

The code below works, it updates a record or creates one if it doesn't exist yet. However, I'd like to combine this findOneAndUpdate()statement with the populate()method in order to populate the "user" of my object. What would be the right way to add the populate("user")statement to this logic?

下面的代码有效,它会更新一条记录,如果尚不存在则创建一条记录。但是,我想将此findOneAndUpdate()语句与populate()方法结合起来,以填充我的对象的“用户”。将populate("user")语句添加到此逻辑的正确方法是什么?

I tried adding the populate()method after the findOneAndUpdatefinishes but that returns an error saying that this method doesn't exist. I'm running the latest version of mongoose.

我尝试populate()findOneAndUpdate完成后添加该方法,但返回一个错误,指出该方法不存在。我正在运行最新版本的猫鼬。

LoyaltyCard.findOneAndUpdate({ business: businessid}, { $set: newCard, $inc: { stamps: +1 } }, { upsert: true}, function(err, card){

    if(err)
    {

    }
    else
    {

    }

    res.json(result);
});

回答by Gergo Erdosi

Use exec()instead of a callback parameter:

使用exec()而不是回调参数:

LoyaltyCard.findOneAndUpdate(
        {business: businessid},
        {$set: newCard, $inc: {stamps: +1}},
        {upsert: true}
    )
    .populate('user')
    .exec(function(err, card) {
        if (err) {
            // ...
        } else {
            res.json(result);
        }
});

回答by davidsonsns

With async/awaitI removed the exec

随着async/await我删除了 exec

const getLoyaltyCard = async () => {
    const results = await LoyaltyCard.findOneAndUpdate(
        { business: businessid },
        { $set: newCard, $inc: { stamps: + 1 } },
        { upsert: true }
    )
    .populate('user')
    return results
}