在 mongoose 中验证其父级范围内的嵌入文档的唯一性 [英] Validating uniqueness of an embedded document scoped by its parent in mongoose

查看:22
本文介绍了在 mongoose 中验证其父级范围内的嵌入文档的唯一性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在猫鼬中有以下架构:

I have the following schema in mongoose:

UserSchema = new Schema
    username: {type: String, required: true}

GameSchema = new Schema
    identifier: String
    users: [UserSchema]

我想确保游戏中的每个用户都有一个唯一的用户名.但是,如果我添加

I want to ensure that every user in a game has a unique username. However, if I add

unique: true

对于用户名定义,它似乎在所有游戏中强制执行唯一性,而不仅仅是在用户所在的游戏中.此外,如果我有 1 个以上没有用户的游戏,则会出现以下错误:

to the username definition, then it seems to enforce uniqueness across all games, not just within the game that the user resides. Also, if I have more than 1 game with no users, then I get the following error:

games.$users.username_1  dup key: { : null }

我尝试向用户名字段添加自定义验证器以手动检查该用户名是否已在父游戏的范围内使用,但在猫鼬中,验证器功能仅接收用户名的实际字符串,所以我不有任何方法可以检查用户名在游戏中是否唯一,因为我无法在验证器函数中获得对父游戏文档的引用.

I tried adding a custom validator to the username field to manually check if that username is already taken within the scope of the parent game, but in mongoose the validator function only receives the actual string of the username, so I don't have any way of checking that the username is unique within the game because I can't get a reference to the parent game document in the validator function.

有没有办法在猫鼬中完成这种验证?

Is there any way to accomplish this sort of validation in mongoose?

推荐答案

正如您所发现的,向数组的字段添加唯一索引不会强制数组内的唯一性,它确保没有两个文档 集合中包含数组中相同的字段值.

As you found out, adding a unique index to a field of an array doesn't enforce uniqueness within the array, it ensures that no two documents in the collection contain the same field value in the array.

相反,请查看 $addToSet 数组运算符作为一种将值原子添加到数组中的方法,仅当它不在数组中时.

Instead, look at the $addToSet array operator as a way of atomically adding a value to an array only if it's not already in the array.

这篇关于在 mongoose 中验证其父级范围内的嵌入文档的唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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