Mongoose Unique values in nested array of objects

前端 未结 2 707
梦如初夏
梦如初夏 2020-11-27 05:02

For my project, I want to keep a mongoose document for groups of organizations, like this:

var groupSchema = Schema({
  name : { type : String },
  org : { t         


        
相关标签:
2条回答
  • 2020-11-27 05:58

    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.

    0 讨论(0)
  • 2020-11-27 06:02

    Well this might be old question but for mongoose > v4.1, you can use $addToSet operator.

    The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.

    example:

    MyModal.update(
       { _id: 1 },
       { $addToSet: {letters: [ "c", "d" ] } }
    )
    
    0 讨论(0)
提交回复
热议问题