Mongoose async / await find然后编辑并保存?

时间:2017-05-31 22:03:28

标签: node.js mongodb asynchronous mongoose

是否可以使用async / await promise进行查找然后保存?

我有以下代码:

try {
    var accounts = await Account.find()
    .where("username").in(["email@gmail.com"])
    .exec();
    accounts.password = 'asdf';
    accounts.save();
} catch (error) {
    handleError(res, error.message);
}

我收到以下错误:

ERROR: accounts.save is not a function

1 个答案:

答案 0 :(得分:9)

这就是我想要的:

try {
    var accounts = await Account.findOneAndUpdate(
        {"username" : "helllo@hello.com"},
        {$set: {"password" : "aaaa"}},
        {new : true}
    );
    res.status(200).json(accounts);
} catch (error) {
    handleError(res, error.message);
}

或(感谢@JohnnyHK查找vs findOne提示!):

try {
    var accounts = await Account.findOne()
    .where("username").in(["hello@hello.com"])
    .exec();
    accounts.password = 'asdf';
    accounts.save();
    res.status(200).json(accounts);
} catch (error) {
    handleError(res, error.message);
}