gpt4 book ai didi

node.js - 在嵌套数组中查找和删除文档

转载 作者:可可西里 更新时间:2023-11-01 10:50:54 25 4
gpt4 key购买 nike

我正在努力删除 mongoDB 中嵌套数组中的元素。

假设我有这个架构:

var question = new Schema({
problem: {
type: String,
required: true
},
multipleChoices: [{
type: String,
required: true
}],
correctAnswer: {
type: Number,
required: true
}
});

var testCategorySchema = new Schema({
category: {
type: String,
required: true
},
tests: [{
version: {
type: String,
required: true
},
questions: [question]
}]
});

例如,我有这样一个模式的实例:

{
category: "Math",
tests: [
{
_id : ObjectId("580859310a0d4b40ac1c6034"),
version: "1A",
questions: [
{
problem: "blablabla",
multiplechoices: [
"bla bla", "blb blb", "blc blc"
],
correctAnswer: 1
},
{
problem: "blibliblibli",
multiplechoices: [
"bla bla", "blb blb", "blc blc"
]
correctAnswer: 1
}
]
},
{
_id : ObjectId("580859310a0d4r40ax1c5034"),
version: "1B",
questions: [
{
problem: "auauauauau",
multiplechoices: [
"bla bla", "blb blb", "blc blc"
]
correctAnswer: 1
},
{
problem: "blibliblibli",
multiplechoices: [
"bla bla", "blb blb", "blc blc"
]
correctAnswer: 1
}
]
}
]
}

例如,如何使用 mongooseJS 删除问题:类别数学和版本 1A 中的“blablabla”?

我已经使用此代码删除了数学类别和版本 1A 中的问题:

TestCategory
.findOne(
{
category: req.params.testCategory,
'tests.version': req.params.testVersion
},
{
'tests.version.$': 1
}
)
.then(function(testVersion) {
res.send(testVersion);
})
.catch(function(err) {
console.log(err);
next(err);
});

例如我搜索数学类别和版本 1A,该代码的结果是这样的:

_id: "580859190a0d4b40ac1c6033",
tests: [
{
_id : ObjectId("580859310a0d4b40ac1c6034"),
version: "1A",
questions: [
{
problem: "blablabla",
multiplechoices: [
"bla bla", "blb blb", "blc blc"
],
correctAnswer: 1
},
{
problem: "blibliblibli",
multiplechoices: [
"bla bla", "blb blb", "blc blc"
]
correctAnswer: 1
}
]
}
]

结果已经过过滤,所以只显示版本1A(虽然仍显示categoryId)。现在我很困惑如何以正确和好的方式删除问题。

最佳答案

您需要将 update 与位置运算符 $ 一起使用为了更新正确的测试然后使用 $pull删除问题:

TestCategory.update(
{
category: 'Math',
'tests.version': '1A'
},
{
$pull: {
'tests.$.questions': { problem: 'blablabla' }
}
}
)

关于node.js - 在嵌套数组中查找和删除文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40146460/

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