【问题标题】:Why getting error when updating MongoDb?为什么更新 MongoDb 时会出错?
【发布时间】:2016-07-19 13:44:34
【问题描述】:

我正在使用 MEAN 堆栈构建后端,但是当我尝试更新数据库中的文档时出现错误:

 topUp = function(name, amount, callback) {
    User.updateOne(
        { "name" : name },
        { $set: { "wallet": amount } },
        function(err, results) {
            console.log(results);
            callback();
        });
 };

TypeError: User.updateOne 不是函数

但是例如findOne() 工作正常:

    User.findOne({
                name: decoded.name
            }, function(err, user) {
                if (err) throw err;

                i

f (!user) {
                return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
            } else {
                //res.json({success: true, info: {wallet: user.wallet, userPic: user.userPic}});
                topUp(decoded.name, amount, function() {
                    User.close();
                });
            }
        });

“用户”是一个 Mongo 模型文件。

【问题讨论】:

  • 因为findOne 是一个预定义函数,而updateOne() 不是。默认情况下,它应该只更新一条记录。您可以使用multi: true 更新多条记录。
  • @MohitBhardwaj 好吧,根据 Mongo 文档 updateOne() 也是预定义的:proof
  • 我认为您可能正在使用的数据库驱动程序中没有定义它。我认为您正在使用 Mongoose 并且 updateOne() 在那里不可用。您不能将所有本机 mongodb 函数与所有驱动程序一起使用。
  • 我不是很确定,但根据我的理解是这样的。
  • @MohitBhardwaj 哇,非常感谢,这是真的!我应该使用 Mongoose 支持的 update() 而不是 updateOne()。如果您将其写为答案,我将很高兴接受它:)

标签: javascript node.js mongodb express


【解决方案1】:

我认为您可能正在使用的数据库驱动程序中没有定义它。我认为您正在使用 Mongoose 并且 updateOne() 在那里不可用。您不能将所有本机 mongodb 函数与所有驱动程序一起使用

【讨论】:

    【解决方案2】:

    对此 https://github.com/Automattic/mongoose/issues/3997 有一个现有的增强请求,但 findByIdAndUpdate() 方法可能是一个不错的选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 2020-03-13
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 2016-02-28
      • 1970-01-01
      相关资源
      最近更新 更多