【问题标题】:Mongoose findByIdAndUpdate() updates the wrong entryMongoose findByIdAndUpdate() 更新错误条目
【发布时间】:2014-02-19 02:31:42
【问题描述】:

我正在调用以下 Mongoose 函数:

User.findByIdAndUpdate(
  '76561198015207414', 
  {}, 
  { upsert: true }
);

在调用它之前,我的 user 集合是空的。运行函数后,我的user收藏添加了这个文档:

{
    "_id": 76561198015207410
}

为什么会更新集合中的错误条目?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您为User 定义的_id 很可能是一个数字:

    var UserSchema = Schema({
        _id : Number,
        /* more */
    });
    

    如果您使用 JavaScript 并将传递给调用的 String 转换为 findByIdAndUpdate 并将其转换为 Number,您会看到精度没有保留:

    > var x=76561198015207414
    > x
    76561198015207410
    

    您会看到变量x 包含您在问题中显示的_id

    您需要切换到Strings 或确保数字不超过Number

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 2021-10-23
      • 2013-08-14
      • 2020-08-12
      • 1970-01-01
      • 2018-08-13
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多