mongo数组内唯一索引的问题

本文探讨了在Mongoose中如何正确使用唯一索引来保证数组字段内对象的唯一性,并介绍了几种实现方法,包括使用$addToSet操作符及条件更新等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前一直认为通过唯一唯一索引可以确保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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值