'Mongoose Schema for Groups (a number of users in one group)
One aspect of my website is that people can join groups according to a specific code provided to them, for example- when we play 'Kahoot' or 'Psych', we have to give a specific code to join the game, here, I am using the same logic to join the user to a group. For people who don't know what I am talking about: I will generate a 3 word code, say, 'absent agitated alive', the user will enter the same thing in the 'Join Group' section and then he can enter the Group.
I want to know how to make the Schema for the different groups and also how to relate groups with users.
This is my current User Schema:
const mongoose=require('mongoose')
const UserSchema=new mongoose.Schema({
googleId:{
type:String,
required:true,
},
displayName:{
type:String,
required:true,
},
firstName:{
type:String,
required:true,
},
lastName:{
type:String,
required:true,
},
image:{
type:String
},
createdAt:{
type:Date,
default:Date.now
}})module.exports=mongoose.model('User',UserSchema)
I want to know how to make the Groups Schema. This is my Groups Schema as of now:
const mongoose = require("mongoose");
const GroupsSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
grp_code: {
type: String,
required: true,
},
users: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
createdAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Group", GroupsSchema);
I want to make the 'users' document in the groups database to be an array, storing the id of all the users who have joined the group. I can't figure out what to do, please help
Solution 1:[1]
Yo can use:
users: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
}],
To define an array of users
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | nimrod serok |