Unique array values in Mongoose Unique array values in Mongoose mongoose mongoose

Unique array values in Mongoose


To my knowledge, the only way to do this in mongoose is to call the underlying Mongo operator (mentioned by danmactough). In mongoose, that'd look like:

var idToUpdate, theIdToAdd; /* set elsewhere */Model.update({ _id: idToUpdate },              { $addToSet: { theModelsArray: theIdToAdd } },              function(err) { /*...*/ });

Note: this functionality requires mongoose version >= 2.2.2


Mongoose is an object model for mongodb, so one option is to treat the document as a normal javascript object.

MyModel.exec(function (err, model) {   if(model.watching.indexOf(watchId) !== -1) model.watching.push(watchId);   model.save(...callback);});

Although, I do agree that mongoose should have some support for this built in the form of a validator for the collection document reference feature-- especially because most of the time you want to add only unique references.