Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mongodb - Validating uniqueness of an embedded document scoped by its parent in 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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...