Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique array values in Mongoose

Currently trailing out Mongoose and MongoDB for a project of mine but come across a segment where the API is not clear.

I have a Model which contains several keys and documents, and one of those keys os called watchList. This is an array of ID's that the user is watching, But I need to be sure that these values stay unique.

Here is some sample code:

var MyObject = new Mongoose.Schema({
    //....
    watching : {type: Array, required: false},
    //....
});

So my question is how can I make sure that the values pushed into the array only ever store one, so making the values unique, can i just use unique: true ?

Thanks

like image 547
RobertPitt Avatar asked Mar 09 '12 20:03

RobertPitt


1 Answers

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

like image 55
frank hadder Avatar answered Oct 07 '22 01:10

frank hadder