将数据插入双嵌套数组

Inserting data into a double-nested array

我会尽量保持简短, 架构如下所示...


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)

如何在代码的斜线部分填写数据?? (即 answers 的评论部分) 我想将 answerId 与评论数据一起传递,以某种方式在整个模式中查找 answerId 并将我的数据填充到此评论部分

您可以使用 $ and $push 来实现。

示例:

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