Mongoose 中的唯一数组值

编程入门 行业动态 更新时间:2024-10-16 00:19:04
本文介绍了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 中的唯一数组值

本文发布于:2023-11-30 16:10:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   Mongoose

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!