Jean-Baptiste Louazel
Jean-Baptiste Louazel

Reputation: 525

Insert an unique object in an object array with mongoose

I'm inserting an object in an array of object with mongoose. My object is like:

   name: {
    type: String,
    unique: true,
    required: true
},
translations: [{
    tag: {
        type: String,
        unique: true,
        required: true
    },
    meaning: {
        type: String,
        required: true
    }
}]

I would like my code to throw an error when there are already an object in "translation" with the same 'tag' value.

I'm currently doing this :

Language.update(
    {name: languageName},
    {$addToSet: { 'translations': {
        tag: aNewTag,
        meaning: aNewTranslation
    }}}, {
        upsert: false
    }, function(err) {
        if (err) console.log(err);
        else console.log('This is spartaaa!!!');
    }
);

Upvotes: 1

Views: 793

Answers (1)

Dennis van der Schagt
Dennis van der Schagt

Reputation: 2414

You could check the WriteResult in the update callback and then throw an error if there was no modification, like this:

Language.update(
  {
    name: languageName
  }, {
    $addToSet: {
      'translations': {
        tag: aNewTag,
        meaning: aNewTranslation
  }}}, {
    upsert: false
  }, function(err, result) {
    if (err) {
      console.log(err);
    } else if (result.nModified === 0) {
      throw Error('Object is not unique, no duplicate inserted.');
    } else {
      console.log('This is spartaaa!!!');
    }
});

More information about the WriteResult for updates can be found in the mongoose documentation.

Upvotes: 1

Related Questions