【问题标题】:Mongoose async/await find then edit and save?猫鼬异步/等待查找然后编辑并保存?
【发布时间】:2017-11-01 21:13:15
【问题描述】:

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

我有以下代码:

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

【问题讨论】:

  • accounts 是找到的文档数组,因此您的代码实际上并没有编辑任何内容。你想在这里做什么?
  • @JohnnyHK 我想我只是在尝试理解猫鼬、查询和承诺(以等待/同步格式)。我想上面的代码没有意义。如果我想查找所有用户名为hello@hello.com 的帐户并将密码更改为asdf 怎么办?我将更改上面的代码以反映这个问题。
  • 这仍然没有任何意义,因为accounts 仍然是一个数组。首先使用findOne 而不是find,这样会更有意义。
  • @JohnnyHK 谢谢!你把我带到了我需要去的地方。现在更有意义了。

标签: node.js mongodb asynchronous mongoose


【解决方案1】:

这就是我要找的东西:

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 与 findOne 的提示!):

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

【讨论】:

    猜你喜欢
    • 2018-08-30
    • 2019-05-10
    • 2019-03-20
    • 2021-01-22
    • 2020-10-16
    • 2018-08-09
    • 2018-11-29
    • 2018-04-13
    • 2019-02-15
    相关资源
    最近更新 更多