您的位置:首页 > 编程语言 > Go语言

mongo数组内唯一索引的问题

2016-11-10 10:07 253 查看
之前一直认为通过唯一唯一索引可以确保doc数组字段的每个doc确保唯一(根据某个字段)如:

staffs: [staffRoleSchema],
const staffRoleSchema = new Schema({
openid: { type: String, index: { unique: true }, sparse: true },
privilege: { type: String, enum: ['general', 'manage', 'insider'] },
}, { _id: false });


后来查了文档,其实在 http://stackoverflow.com/questions/15921700/mongoose-unique-values-in-nested-array-of-objects
30
down vote
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.

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}}, ...
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) { ... });
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐