在猫鼬独特的数组值 [英] Unique array values in Mongoose

查看:135
本文介绍了在猫鼬独特的数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前拖出猫鼬和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

这篇关于在猫鼬独特的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆