对于我的项目,我想为组织组保留一份mongoose文档,如下所示:
var groupSchema = Schema({
name : { type : String },
org : { type : Schema.Types.ObjectId, ref : 'Organization' },
...
users : [{
uid : { type : Schema.Types.ObjectId, ref : 'User' },
...
}]
});
Run Code Online (Sandbox Code Playgroud)
我想阻止同一个用户在同一组中两次.为此,我需要强制users.uid在users数组中是唯一的.我尝试为uid说明'unique:true',但这不起作用.有没有办法用mongoose或mongoDB执行此操作而无需额外查询或拆分架构?
编辑:我将uid的先前值更改为uid:{type:Schema.Types.ObjectId,ref:'User',index:{unique:true,dropDups:true}}但是这似乎仍然不起作用.
编辑:假设没有简单的方法来实现这一点,我添加了一个额外的查询检查用户是否已经在组中.在我看来,这是最简单的方法.