gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:17:55 25 4
gpt4 key购买 nike

假设我创建了一个如下所示的模型:

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"
}
]
}

在 session 内的一个出勤数组中推送新元素的最佳方式是什么?

就像我想插入这个:

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

使用 sessionName: "Session1" 进入对象中的 attendances 数组,这样文档将如下所示:

{
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"
}
]
}

此外,如果我已经成功地将新元素推送到该数组上,我将如何删除该数组上的特定元素?

最佳答案

您可以使用$ 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" } } })

关于node.js - 更新子文档中的数组 - mongoose mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53102925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com