Saturday 24 August 2019

How would I better model this relationship in mongodb using mongoose to query easily?

Relationship: User and communityuser can join different communities.communities can have multiple users just like reddit.Query:list the members of a communitylist the communities that a member belongs tolist all communities and list all membersCurrent Model:const userSchema = mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, isVerified: { type: Boolean, default: false } }); const communitySchema = mongoose.Schema({ name: { type: String, required: true, unique: true }, members: [ { type: mongoose.Schema.Types.ObjectId, ref: User } ] }); With this model,I can list all members and community and also list members of a particular community but not able to list all the community that a member belong to..If that query is possible with this model, orIf it has to modelled differently also, please let me know.Ps: Yes, thought about having another ref in the user model that points to the community but wouldn't that have a duplicate write when users joins a community?I have push userid into the particular community and community id into user model. So I thought there would be a better way.

Submitted August 24, 2019 at 11:09AM by sum__sleples

No comments:

Post a Comment