Home > database >  Proper way to store documents in MongoDB
Proper way to store documents in MongoDB

Time:03-17

I've been having this same question about MongoDB for the longest time. So I'm trying to store some user data for users who invite my discord bot to their guild. It stores them based off guild ID and user ID, because one user could be in multiple servers with the same bot. I was wondering if it would be correct to make one document for each guild and add every user to that one document, or should I make a separate document for each user with a guild ID key and user ID key.

For example I've attached 2 photos to this post, the first features one document with a "Users" field nested into an object with the key as the guild ID used for querying. The second features a separate document for each user with a separate "User ID" and "Guild ID" key used for querying.

Single Document File

Multi Document File

Any and all help is appreciated. Thank you in advance.

CodePudding user response:

This is an idea what you can do. This way you can fetch data and aggregate any way you like, and you won't be having any unnecessary nesting. Simple and flexible

// Guild Schema

{
  guildId: Number,
  guildName: String,
  other: String
}

// User Schema

{
  userId: Number,
  guild: {
    type: Schema.Types.ObjectId,
    ref: "Guild"
  },
  userInfo:{
    name: String,
    address: String,
    other: String
  }
}
  • Related