0

I'll try to keep it short and simple, The schema looks like below...


import mongoose from 'mongoose'

const QuestionSchema = mongoose.Schema({
    questionTitle: { type: String, required: " title"},
    questionBody: { type: String, required: "body"}
    userId: { type: String},
    askedOn: { type: Date, default: Date.now},
    Comment:[{
        commentBody: String,
        userCommented: String,
        userId: String,
        commentedOn: { type: Date, default: Date.now},
    }],
    answer: [{
        answerBody: String,
        userAnswered: String,
        userId: String,
        answeredOn: { type: Date, default: Date.now},
        Comment:[{                      
            commentBody:String,          ////
            userCommented: String,       ////
            userId: String,              ////  
            commentedOn: { type: Date, default: Date.now},         ////
        }]
    }]
})

export default mongoose.model("Question", QuestionSchema)

How do i fill data in the slashed part of code?? ( i.e comment section of answers) i wanted to pass answerId with the comment data, to somehow look for that answerId in whole schema and fill my data into this comment section

1 Answers1

0

You can do achieve this using $ and $push.

Example:

const updateTheCol =  await Question.updateOne(
    { "answer.userId": "user id" }, 
    { $push: { 
        "answer.$.Comment": { 
            commentBody: "comment body", 
            userCommented: "user commented",
            userId: "user id"
        }
    } 
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31