猫鼬upsert重复密钥错误 [英] Mongoose upsert duplicate key error
问题描述
我正在尝试使用Mongoose进行upsert,但是对于应该触发upsert的密钥,我得到了重复的密钥错误.
I'm trying do an upsert using Mongoose, but I'm getting a duplicate key error for the very key that should trigger the upsert.
模式:
"resource": {type: Schema.ObjectId, ref: "Resource"},
"skill": {type: Schema.ObjectId, ref: "Skill"},
"level": {type: Number, min: 1, max: 5}
.index({skill: 1, resource: 1}, {unique: true});
然后我打电话:
//self is a Resource instance
ResourceSkillLevel.update({
resource: self._id,
skill: skill._id,
level: level
}, {$set: {level: level}}, {upsert: true}, cb);
如果(resource, skill)
不存在,则此调用可以正常工作并正确创建ResourceSkillLevel
条目.但是,当我再次调用它时,会得到duplicate key error index
.列出的重复键是元组资源/技能键.找到重复项时为什么不上调?
If the (resource, skill)
does not exist, this call works just fine and properly creates the ResourceSkillLevel
entry. However, when I call it again I get duplicate key error index
. The listed duplicate key is the tuple resource/skill key. Why isn't it upserting when it finds the duplicate?
推荐答案
您要在update
查询条件参数中包含level
,因此,如果该参数也与现有记录不匹配,它将尝试创建一个新文档将使唯一索引失败,该唯一索引仅跨越skill
和resource
.
You're including level
in the update
query criteria parameter, so if that doesn't also match the existing record it will try and create a new doc which will fail the unique index which only spans skill
and resource
.
尝试将您的update
更改为此:
ResourceSkillLevel.update({
resource: self._id,
skill: skill._id
}, {$set: {level: level}}, {upsert: true}, cb);
这篇关于猫鼬upsert重复密钥错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!