Mongoose async/await find then edit and save?

后端 未结 1 1869
耶瑟儿~
耶瑟儿~ 2021-02-08 09:46

Is it possible to do a find then save using async/await promise?

I have the following code:

try {
    var accounts = await Account.find()
    .where(\"us         


        
相关标签:
1条回答
  • 2021-02-08 10:32

    This is what I was looking for:

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

    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);
    }
    
    0 讨论(0)
提交回复
热议问题