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

问题描述 投票:7回答:1

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

我有以下代码:

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

我收到以下错误:

ERROR: accounts.save is not a function
node.js mongodb asynchronous mongoose
1个回答
8
投票

这就是我要找的东西:

try {
    var accounts = await Account.findOneAndUpdate(
        {"username" : "[email protected]"},
        {$set: {"password" : "aaaa"}},
        {new : true}
    );
    res.status(200).json(accounts);
} catch (error) {
    handleError(res, error.message);
}

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

try {
    var accounts = await Account.findOne()
    .where("username").in(["[email protected]"])
    .exec();
    accounts.password = 'asdf';
    accounts.save();
    res.status(200).json(accounts);
} catch (error) {
    handleError(res, error.message);
}
© www.soinside.com 2019 - 2024. All rights reserved.