I am working on a node/express web API with a mongo database.

However, there is something I am not sure about the database schema I should use.

Let's say I have two collections: post, comment.


First option :

const postSchema = new mongoose.Schema({
    title: { type: String, required: true },
    content: { type: type: String, required: true },
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
}, { timestamps: true })

const commentSchema = new mongoose.Schema({
    content: { type: type: String, required: true }
}, { timestamps: true })

Which would allow me to get all comment of a post in one query, but it seems weird to not have the postId in the comment, if I want to select all comment of a post, I have to query the whole post.


Second option :

const postSchema = new mongoose.Schema({
    title: { type: String, required: true },
    content: { type: type: String, required: true }
}, { timestamps: true })

const commentSchema = new mongoose.Schema({
    content: { type: type: String, required: true },
    post: { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }
}, { timestamps: true })

I don't really see downsides except that I now need to execute a second query to get a post comments.


Third option :

const postSchema = new mongoose.Schema({
    title: { type: String, required: true },
    content: { type: type: String, required: true },
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
}, { timestamps: true })

const commentSchema = new mongoose.Schema({
    content: { type: type: String, required: true },
    post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }
}, { timestamps: true })

Which would be the easiest way to use when developing (not saying other two are hard, tho) because I could get all comment of a post without selecting the post itself, or selecting the post and get all the comment without running a second query. But the structure seems a bit clumsy


I know fourth option would be to use a relationnal database since but sadly I can't.

So which option would be the general recommended to do oneToMany with mongodb ?

0 Answers