【问题标题】:Calling save on doc with _id is calling insert使用 _id 在 doc 上调用 save 是调用 insert
【发布时间】:2015-07-12 21:57:56
【问题描述】:

我有以下文件:

{ 
  _id: 552bdc73789d083b15e3d6d5,
  username: 'test',
  firstname: 'test',
  lastname: 'test'
}

当我对该文档调用 save 时,mongoose 正在运行插入。

这会导致 mongo 为 _id 字段抛出重复键错误,因为它已经存在。

知道为什么 mongoose 会在我从数据库中检索到的已经存在的文档上调用 insert 吗?

编辑:

使用 mongoose 4.0.2 和 mongo 2.6。

这是我检索文档的方式:

var getUserByUsername = function(username, callback) {
  User.findOne({username: username.toLowerCase()}).exec(function(err, user) {
    callback(err, user);
  });
}

然后某个时候我在那个用户对象上调用 save:

var updateUser = function(user, callback) {
  user.save(function(err) {
    if (err) {  // this is where I see the error
      console.log('Could not update user ' + user.username + ' error ',  err);
    }

    callback(err, user)
  });
}

编辑 2:

我如何真正检索文档:

   Other.findOne({name: name}).populate({path: 'userId', options: {lean: true}}).exec(function(err, token) {
       ...
    }

对 userId 进行精益填充以填充用户似乎是问题所在。

【问题讨论】:

  • 当然可以@JohnnyHK,很抱歉遗漏了可能是最重要的部分;)
  • 该代码看起来不错。在您调用 user.save 之前,user.isNew 布尔标志会显示什么?它应该是 false 与现有的文档,这将导致 update 而不是 insert
  • isNew 返回真。这让我回顾了代码并意识到当我最初告诉你我是如何得到文档时我撒了谎:( 感谢@JohnnyHK 引导我解决问题。

标签: node.js mongodb mongoose


【解决方案1】:

问题是在堆栈中进一步填充的精益选项。感谢@JohnnyHK 为我指路,我开始检查 isNew 直到发现问题。

引发问题的原始查询:

Other.findOne({name: name}).populate({path: 'userId', options: {lean: true}}).exec(function(err, token) { ... }

那时我有一个精益用户。这种用法已经流传下来,我稍后会尝试更新它。

至少从 4.0.2 开始,文档是精简的(不是 mongoose 对象),即使它具有 _id save() 也不起作用。我确信这符合预期,并且我的代码已更改,删除了精益查询。

【讨论】:

    猜你喜欢
    • 2013-03-21
    • 2017-04-04
    • 1970-01-01
    • 2013-08-29
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多