Mongoose - Single object in an array

2

I'm new to MongoDB and Mongoose, I'd like to ask a question.

I would like to store multiple objects in an array, and the object must be ONLY ONLY in that array, based on a string. See the example below:

var list = {
  name: "List 1",
  recipients: [
    // esse e-mail deve ser único NESSE array, mas, caso eu crie outro objeto 'list', ele pode ser adicionado novamente...
    {
      email: "[email protected]"
    },
    {
      email: "[email protected]"
    }
  ]
}

var list2 = {
  name: "List 2",
  recipients: [
    // essa é uma nova lista, vejam que posso adicionar o [email protected] nessa nova lista
    {
      email: "[email protected]"
    },
    {
      email: "[email protected]"
    }
  ]
}

var list3 = {
  name: "List 3",
  recipients: [
    // já isso eu não quero que aconteça, vejam que existe 2 [email protected], isso eu NÃO quero...
    {
      email: "[email protected]"
    },
    {
      email: "[email protected]"
    }
  ]
}

See how my Schema is:

var ListSchema = new Schema({
  name: String,
  recipients: [
    {
      email: {
        type: String,
        unique: true
      }
    }
  ]
});
    
asked by anonymous 31.05.2016 / 15:35

1 answer

1

The unique prevents duplication of documents in the collection, not items in the array.

Use the $addToSet operator to add a value to an Array only if the value is not present.

var where = {_id: listId};
var update = {$addToSet: {recipients: userObj}};
List.update(where, update, function(err, numAffected) { ... });

However, if you want to ensure uniqueness in only one field of the object, not the entire object, do so:

var where = {_id: listId, 'recipients.email': {$ne: userObj.email}};
var update = {$push: {recipients: userObj}};
List.update(where, update, function(err, numAffected) { ... }); 
    
31.05.2016 / 16:55