Mongoose async / await find then edit and save?

Is it possible to do a search and then save using an asynchronous / pending promise?

I have the following code:

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

and I get the following error:

ERROR: accounts.save is not a function
+4
source share
1 answer

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 help and tipOne!):

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);
}
+5
source

Source: https://habr.com/ru/post/1678297/


All Articles