Mongoose - Single object in an array

Asked

Viewed 1,163 times

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, the object being ONLY unique in that array, based on a string. See in 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]"
    }
  ]
}

Look at my Schema:

var ListSchema = new Schema({
  name: String,
  recipients: [
    {
      email: {
        type: String,
        unique: true
      }
    }
  ]
});

1 answer

1


The index unique avoids duplicity of documents in the collection, not items in the array.

Use the operator $addToSet 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 oneness in just one field of the object, and not the whole object, do so:

var where = {_id: listId, 'recipients.email': {$ne: userObj.email}};
var update = {$push: {recipients: userObj}};
List.update(where, update, function(err, numAffected) { ... }); 
  • Obg, I’ll try to use that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.