猫鼬异步/等待找到然后编辑并保存? [英] Mongoose async/await find then edit and save?

查看:85
本文介绍了猫鼬异步/等待找到然后编辑并保存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用异步/等待承诺进行查找然后保存?

Is it possible to do a find then save using 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

推荐答案

这就是我想要的:

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的find vs findOne技巧!)

or (thanks @JohnnyHK for the find vs findOne tip!):

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);
}

这篇关于猫鼬异步/等待找到然后编辑并保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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