更新子文档中的数组-mongoose mongodb

时间:2018-11-01 14:04:52

标签: node.js mongodb mongoose

假设我创建了一个像这样的模型:

const attendance = mongoose.Schema({
    studentName: {type: String, required: true},
    status: {type: Number, required: true}
});

const session = mongoose.Schema({
    sessionName: {type: String, required: true},
    attendances: {type: [attendance]}
});

const subjectSchema = mongoose.Schema({
    name: {type: String, required: true},
    faculty_ID: {type: String, required: true},
    students: {type: [String]},
    sessions: {type:[session]} 
});

module.exports = mongoose.model('Subject', subjectSchema);

其中的示例文档如下:

{
    students: [
        "Student1",
        "Student2",
        "Student3"
    ],
    _id: "5bd5a6f49097cd505cf6317a",
    name: "subjectName",
    faculty_ID: "5bd57383bbe10f4f6439ae43",
    sessions: [
        {
            attendances: [ ],
            _id: "5bd6c4de95ffe03480ee8796",
            sessionName: "Session1"
        },
        {
            attendances: [ ],
            _id: "5bd7a9d2604b760004947833",
            sessionName: "Session2"
        },
        {
            attendances: [ ],
            _id: "5bd7a9e4604b760004947834",
            sessionName: "Session3"
        }
    ]
}

在会话内的出席数组之一中推送新元素的最佳方法是什么?

就像我要推送的内容:

{
    studentName: "Student1",
    status: "Present"
}

使用sessionName: "Session1"进入对象的出席数组,这样文档便如下所示:

{
    students: [
        "Student1",
        "Student2",
        "Student3"
    ],
    _id: "5bd5a6f49097cd505cf6317a",
    name: "subjectName",
    faculty_ID: "5bd57383bbe10f4f6439ae43",
    sessions: [
        {
            attendances: [
               {
                   studentName: "Student1",
                   status: "Present"
               }
            ],
            _id: "5bd6c4de95ffe03480ee8796",
            sessionName: "Session1"
        },
        {
            attendances: [ ],
            _id: "5bd7a9d2604b760004947833",
            sessionName: "Session2"
        },
        {
            attendances: [ ],
            _id: "5bd7a9e4604b760004947834",
            sessionName: "Session3"
        }
    ]
}

此外,如果我已经成功地在该阵列上推出了新元素,该如何删除该阵列上的特定元素?

1 个答案:

答案 0 :(得分:2)

您可以使用$ positional operator来指示应修改哪个session。试试:

Model.updateOne({ _id: "5bd5a6f49097cd505cf6317a", "sessions._id": "5bd6c4de95ffe03480ee8796" }, 
    { $push: { "sessions.$.attendances": {  studentName: "Student1", status: "Present" } } })

要删除该值,您需要使用相同的运算符和以条件作为参数的$pull,例如:

Model.updateOne({ _id: "5bd5a6f49097cd505cf6317a", "sessions._id": "5bd6c4de95ffe03480ee8796" }, 
    { $pull: { "sessions.$.attendances": {  studentName: "Student1" } } })