问题描述
我的猫鼬具有以下架构:
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.
这篇关于验证嵌入式文档的唯一性(其父级范围为猫鼬)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!