Mongodb 验证mongoose中由其父级限定范围的嵌入文档的唯一性

Mongodb 验证mongoose中由其父级限定范围的嵌入文档的唯一性,mongodb,mongoose,Mongodb,Mongoose,我在mongoose中有以下模式: UserSchema = new Schema username: {type: String, required: true} GameSchema = new Schema identifier: String users: [UserSchema] 我想确保游戏中的每个用户都有一个唯一的用户名。不过,如果我补充一点 unique: true 在用户名定义中,它似乎在所有游戏中强制执行唯一性,而不仅仅是在用户所在的游戏中。此外

我在mongoose中有以下模式:

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

GameSchema = new Schema
    identifier: String
    users: [UserSchema]
我想确保游戏中的每个用户都有一个唯一的用户名。不过,如果我补充一点

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

games.$users.username_1  dup key: { : null }
我尝试在用户名字段中添加一个自定义验证器,以手动检查该用户名是否已在父游戏的范围内,但在mongoose中,验证器函数仅接收用户名的实际字符串,因此,我没有任何方法检查用户名在游戏中是否唯一,因为我无法在validator函数中获得对父游戏文档的引用


在mongoose中有什么方法可以完成这种验证吗?

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


相反,将数组运算符视为一种仅在数组中没有值时才向数组中原子添加值的方法。

这可以通过执行以下操作轻松实现:

doc.array.addToSet(4,5);
doc.array.pull(4,5);
doc.array.remove(4,5); //alias of .pull()
您可以通过执行以下操作来删除它们:

doc.array.addToSet(4,5);
doc.array.pull(4,5);
doc.array.remove(4,5); //alias of .pull()