Unique array values in Mongoose

萝らか妹 提交于 2019-12-18 07:36:35

问题


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


回答1:


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




回答2:


Take a look at the Mongo documentation on the $addToSet operator.




回答3:


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.



来源:https://stackoverflow.com/questions/9640233/unique-array-values-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!