1

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!!!');
    }
);
2
  • 1
    I don't think this is possible with one operation in MongoDb. You will have to check the document first, and then update or throw the exception. Commented Mar 2, 2014 at 23:10
  • It think you are missing the meaning of $addToSet. The point is that it will keep things unique. Anything value you pass in that is already there will not update the array/set. If your items are not unique already, you don't have a set. Commented Mar 3, 2014 at 0:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.