Mongoose 中的唯一数组值 [英] Unique array values in Mongoose

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

问题描述

目前正在为我的一个项目跟踪 Mongoose 和 MongoDB,但遇到一个 API 不清楚的部分.

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

我有一个包含多个键和文档的模型,其中一个键称为 watchList.这是用户正在观看的一组 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.

这是一些示例代码:

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

所以我的问题是如何确保推入数组的值只存储一个,从而使值唯一,我可以只使用 unique: true 吗?

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 ?

谢谢

推荐答案

据我所知,在 mongoose 中执行此操作的唯一方法是调用底层 Mongo 操作符 (由 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

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

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