问题描述
对于我的项目,我想为一组组织保留猫鼬的文档,如下所示:
For my project, I want to keep a mongoose document for groups of organizations, like this:
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声明"unique:true",但这没有用.有没有办法用mongoose或mongoDB做到这一点,而无需额外的查询或拆分模式?
I want to prevent the same user from being in the same group twice. To do this, I need to force users.uid to be unique in the users array. I tried stating 'unique : true' for uid, but that didn't work. Is there a way to do this with mongoose or mongoDB without extra queries or splitting the schema?
我将uid的先前值更改为 uid:{type:Schema.Types.ObjectId,ref:'User',索引:{unique:true,dropDups:true}}但这似乎仍然行不通.
I changed the previous value of uid to uid : { type : Schema.Types.ObjectId, ref : 'User', index: {unique: true, dropDups: true} }But this still doesn't seem to work.
假设没有简单的方法可以实现此目的,我添加了一个额外的查询来检查用户是否已经在组中.在我看来,这是最简单的方法.
Assuming there is no simple way to achieve this, I added an extra query checking if the user is already in the group. This seems to me the simplest way.
推荐答案
数组字段上的唯一索引会强制相同的值不能出现在集合中多个 document 的数组中,但不会阻止同一个值在单个文档的数组中出现多次.因此,当您向数组中添加元素时,您需要确保唯一性.
A unique index on an array field enforces that the same value cannot appear in the arrays of more than one document in the collection, but doesn't prevent the same value from appearing more than once in a single document's array. So you need to ensure uniqueness as you add elements to the array instead.
使用 $addToSet
运算符仅将值添加到数组如果该值尚不存在.
Use the $addToSet
operator to add a value to an array only if the value is not already present.
Group.update({name: 'admin'}, {$addToSet: {users: userOid}}, ...
但是,如果users
数组包含具有多个属性的对象,并且您想确保仅其中一个对象(在本例中为uid
)具有唯一性,那么您需要采取另一种方法:
However, if the users
array contains objects with multiple properties and you want to ensure uniqueness over just one of them (uid
in this case), then you need to take another approach:
var user = { uid: userOid, ... };
Group.update(
{name: 'admin', 'users.uid': {$ne: user.uid}},
{$push: {users: user}},
function(err, numAffected) { ... });
这符合条件,只有在users
的任何元素的uid
字段中不存在user.uid
的情况下,才进行$push
更新.因此,它模仿了$addToSet
行为,但仅模仿了uid
.
What that does is qualify the $push
update to only occur if user.uid
doesn't already exist in the uid
field of any of the elements of users
. So it mimics $addToSet
behavior, but for just uid
.
这篇关于嵌套对象数组中的猫鼬唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!