Mongoose: Reference schema in properties or add as an array? which is better

Viewed 206

For example if i have two schemas User and Post , should i add User reference in Post's properties, or add Post schema as an array inside User Schema? which is better performance wise( and other aspects).

 var PostSchema = new mongoose.Schema({
    title: String,
    postedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
});

OR

var UserSchema = new mongoose.Schema({
    name: String,
    posts: [PostSchema]
});
2 Answers
var PostSchema = new mongoose.Schema({
    title: String,
    postedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
});

I think this way is better than others.

You should have a reference to the user in the PostSchema.

This is the better approach because a user can have multiple posts and if you save the posts in the UserSchema as an array, that array can grow infinitely. This can cause problems because there's a limit on the max size of a mongodb document. Single mongodb document cannot be greater than 16Mb.

Saving Posts in the User schema is better from the performance perspective but considering the limit on the size of mongodb document and the fact that a user can have many posts, a child document (Post) referencing its parent document (User) is the better approach here.

Related