0

I have a user schema like this,

const userSchema = new Schema({
    username: {
        type: String,
    },
    email: {
        type: String,
    },
    thumbnail: {
        type: String,
        default: backendURL + "images/blank-profile.png"
    }
})

and I have a image schema which has embed user object like this,

const imageSchema = new Schema({
    src: {
        type: String,
    },
    name: {
        type: String,
    },
    user: {
        id: { type: String, required: true },
        thumbnail: { type: String },
        username: { type: String }
    },
    comments: [{
     comment: String,
      user: {
        id: { type: String, required: true },
        thumbnail: { type: String },
        username: { type: String }
     },
}]
})

this is working well but there is a problem. When an user try to change thumbnail or username I need to update whole images and images's comments which has any relation with the user.I think this will be really heavy query. Another option is that, if I make my image schema like this

const imageSchema = new Schema({
    src: {
        type: String,
    },
    name: {
        type: String,
    },
    user:{type: String},
    comments: [{
     comment: String,
      userId:String
   }]
})

and when I get images I also run query for users and in this way I will get the images with user's informations. But It can be heavy code too because I will run query for all users. but if I make this I won't need to update user when a user change own thumbnail or username.

I don't know which aproach is best for my situation. Do you guys have any idea or any other solution?

hasankzl
  • 666
  • 4
  • 16
  • 1
    you can use [populate](https://mongoosejs.com/docs/populate.html) and [refer](https://stackoverflow.com/questions/38051977/what-does-populate-in-mongoose-mean), instead of duplicate user date set only `userId` in image schema for user and comment fields. – turivishal Aug 12 '20 at 10:53
  • 1
    this is what I looking for . Thanks @turivishal. – hasankzl Aug 12 '20 at 19:58

0 Answers0