使用 _id 在 doc 上调用 save 调用 insert
Calling save on doc with _id is calling insert
我有以下文件:
{
_id: 552bdc73789d083b15e3d6d5,
username: 'test',
firstname: 'test',
lastname: 'test'
}
当我在该文档上调用保存时 mongoose 是 运行 插入。
这会导致 mongo 为 _id 字段抛出重复键错误,因为它已经存在。
知道为什么 mongoose 会在我从数据库中检索到的已存在的文档上调用插入吗?
编辑:
使用 mongoose 4.0.2 和 mongo 2.6.
这是我检索文档的方法:
var getUserByUsername = function(username, callback) {
User.findOne({username: username.toLowerCase()}).exec(function(err, user) {
callback(err, user);
});
}
然后稍后我在该用户对象上调用保存:
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 为我指明了方向,我开始向上检查 isNew 直到发现问题。
引发问题的原始查询:
Other.findOne({name: name}).populate({path: 'userId', options: {lean: true}}).exec(function(err, token) {
...
}
那时我有一个瘦用户。该用途已通过,我稍后会尝试更新它。
至少从 4.0.2 开始,文档是精简的(不是 mongoose 对象),即使它有一个 _id save() 也不起作用。我确信这是预期的,我的代码已经更改,删除了精益查询。
我有以下文件:
{
_id: 552bdc73789d083b15e3d6d5,
username: 'test',
firstname: 'test',
lastname: 'test'
}
当我在该文档上调用保存时 mongoose 是 运行 插入。
这会导致 mongo 为 _id 字段抛出重复键错误,因为它已经存在。
知道为什么 mongoose 会在我从数据库中检索到的已存在的文档上调用插入吗?
编辑:
使用 mongoose 4.0.2 和 mongo 2.6.
这是我检索文档的方法:
var getUserByUsername = function(username, callback) {
User.findOne({username: username.toLowerCase()}).exec(function(err, user) {
callback(err, user);
});
}
然后稍后我在该用户对象上调用保存:
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 为我指明了方向,我开始向上检查 isNew 直到发现问题。
引发问题的原始查询:
Other.findOne({name: name}).populate({path: 'userId', options: {lean: true}}).exec(function(err, token) { ... }
那时我有一个瘦用户。该用途已通过,我稍后会尝试更新它。
至少从 4.0.2 开始,文档是精简的(不是 mongoose 对象),即使它有一个 _id save() 也不起作用。我确信这是预期的,我的代码已经更改,删除了精益查询。