Home > Net >  Inserting data into a double-nested array
Inserting data into a double-nested array

Time:01-29

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

CodePudding user response:

You can do achieve this using $ and $push.

const updateTheCol =  await Question.updateOne(
 { "answer.userId": "user id" }, 
 { $push: { 
"answer.$.Comment": { 
  commentBody: "comment body", 
  userCommented: "user commented",
  userId: "user id" }
 } 
})
  •  Tags:  
  • Related