Mongoose Unique values in nested array of objects

node.jsMongodbMongoose

node.js Problem Overview


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' },
    ...
  }]
});

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?

Edit: 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.

Edit: 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.

node.js Solutions


Solution 1 - node.js

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.updateOne({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.updateOne(
    {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.

Solution 2 - node.js

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" ] } }
)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuido PassageView Question on Stackoverflow
Solution 1 - node.jsJohnnyHKView Answer on Stackoverflow
Solution 2 - node.jsAnkit BalyanView Answer on Stackoverflow