因此,我有一个具有嵌套配置文件属性的用户模式,并且希望确保当配置文件属性存在时,所有配置文件id都是唯一的:
UserSchema = new Schema {
...
...
profile : {
id : {
type : String
unique : true
sparse : true
}
...
...
}
}但是,在运行测试时,我可以使用相同的profile.id值保存两个不同的用户。是否在嵌套文档上不强制使用唯一属性?我是不是遗漏了什么?
打开日志之后,我可以看到这样的输出(我移除了大部分字段):
Mongoose: users.ensureIndex({ email: 1 }) { safe: undefined, background: true, unique: true }
Mongoose: users.insert({ profile: { id: '31056' }) {}
Mongoose: users.ensureIndex({ 'profile.id': 1 }) { safe: undefined, background: true, sparse: true, unique: true }
Mongoose: users.insert({ profile: { id: '31056' }) {}重复的值仍在插入中。
发布于 2013-04-05 03:25:35
Aaron的建议修正了创建异步索引所导致的争用条件。我等待执行用户架构的单元测试,直到发出索引事件:
User.on('index', function (err) { ... })发布于 2013-04-02 21:12:30
也许它只在嵌套属性中验证为唯一。我自己从来不相信unique,总是进行手动验证,这样我就可以有更多的控制:
我从未在“猫鼬”中使用过嵌套文档,也不确定它是否有效,但至少让您有一个想法:
User.schema.path('profile.id').validate(function(value, respond) {
mongoose.models["User"].findOne({ profile.id: value }, function(err, exists) {
respond(!!exists);
});
}, 'Profile ID already exists');https://stackoverflow.com/questions/15774314
复制相似问题