在Mongoose中使用“unique”与嵌套对象

时间:2013-04-02 21:02:14

标签: node.js mongodb mongoose

所以我有一个带有嵌套 profile 属性的用户模式,我想确保当profile属性存在时所有profile 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' }) {}

仍在插入重复值。

2 个答案:

答案 0 :(得分:2)

也许它只在嵌套属性中验证为唯一。我从不信任unique我自己,总是去手动验证,这样我可以有更多的控制权:

从未在Mongoose中使用过nestes文件,并且不确定它是否有效,但至少让你有一个想法:

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');

答案 1 :(得分:0)

Aaron的建议修复了索引被创建为异步导致的竞争条件。我等待执行我的用户模式的单元测试,直到发出索引事件:

User.on('index', function (err) { ... })
相关问题