【发布时间】:2013-04-02 01:11:18
【问题描述】:
对于我的项目,我想为组织组保留一个 mongoose 文档,如下所示:
var groupSchema = Schema({
name : { type : String },
org : { type : Schema.Types.ObjectId, ref : 'Organization' },
...
users : [{
uid : { type : Schema.Types.ObjectId, ref : 'User' },
...
}]
});
我想防止同一个用户两次出现在同一个组中。为此,我需要强制 users.uid 在 users 数组中是唯一的。我尝试为 uid 声明“唯一:真”,但这没有用。有没有办法用 mongoose 或 mongoDB 做到这一点,而无需额外的查询或拆分架构?
编辑: 我将之前的 uid 值更改为 uid : { type : Schema.Types.ObjectId, ref : 'User', index: {unique: true, dropDups: true} } 但这似乎仍然不起作用。
编辑:假设没有简单的方法来实现这一点,我添加了一个额外的查询来检查用户是否已经在组中。在我看来这是最简单的方法。
【问题讨论】:
-
检查这将是helpful
-
感谢您的链接。我尝试了以下方法: uid : { type : Schema.Types.ObjectId, ref : 'User', index: {unique: true, dropDups: true} } 而不是 uid 的旧值。这仍然不起作用,我也尝试重新启动 mongoDB 没有成功。