在猫鼬独特的数组值

问题描述:

目前拖出猫鼬和MongoDB我的一个项目,但遇到一个细分市场,该API目前尚不清楚。

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

我有一个包含几个键和文件,以及那些按键操作系统名为监视列表的一个模型。这是ID的用户正在观看的数组,但我需要确保这些值保持唯一的。

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.

下面是一些示例code:

Here is some sample code:

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

所以我的问题是我如何才能确保这些值推入阵永远只能存储一个,所以使得价值独特,可我只是使用独特:真正的

感谢

据我所知,在猫鼬做到这一点的唯一方法是调用底层蒙戈运营商(的由danmactough 提及)。在猫鼬,那会是这样的:

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) { /*...*/ }
);

注:此功能需要獴版本> = 2.2.2

Note: this functionality requires mongoose version >= 2.2.2