Tuesday 20 October 2020

single chained query mongodb / mongoose to fetch all comments

I am trying to develop a personal project, a website that functions in a similair way to Stack Exchange, a user can ask a question which can receive multiple answers. Each question and answer can have multiple comments.

I am using nodeJS for my backend.

How can I fetch all comments for all the answers on a particular question in a single mongoDB / mongoose query?

It would be even more helpful if you could tell me how to fetch all comments for all the answers on a particular question as well as all the comments for the question in a single mongoDB / mongoose query?

Mongoose Schemas:

const questionSchema = new mongoose.Schema({
    title: String,
    content: String
})

const answerSchema = new mongoose.Schema({
    questionId: String,
    content: String,
})

const commentSchema = new mongoose.Schema({
    idQuestion: String, // nullable
    idAnswer: String, // nullable
    content: String
})

Currently, I am performing a mongoose query to find all the answers for a particular questions. Then, using forEach, performing a mongoose query on each answer to find all the comments for each answer. I believe this is very taxing, performance wise and is not an ideal way to do what I would like to achieve.



from single chained query mongodb / mongoose to fetch all comments

No comments:

Post a Comment