Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose async/await find then edit and save?

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("username").in(["[email protected]"])
    .exec();
    accounts.password = 'asdf';
    accounts.save();
} catch (error) {
    handleError(res, error.message);
}

and I am getting the following error:

ERROR: accounts.save is not a function
like image 735
Dev01 Avatar asked May 31 '17 22:05

Dev01


Video Answer


1 Answers

This is what I was looking for:

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

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

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);
}
like image 161
Dev01 Avatar answered Oct 10 '22 22:10

Dev01