node.js - 猫鼬在NodeJS中的数组数组中更新值
问题描述
我的测试架构:
var TestSchema = new Schema({
testName: String,
topic: {
topicTitle: String,
topicQuestion: [
{
questionTitle: String,
choice: [
{
name: String
age: Number
}
]
}
]
}
}, { collection: 'test' });
var Test = mongoose.model('test', TestSchema);
我想更新一个我有选择 ID 的年龄($inc) 值。
我可以有test id、topicQuestion id和choice id。
如何在 NodeJS 中用猫鼬编写这个查询?
通常我使用下面的查询来更新一个值:
Test.findOneAndUpdate({ _id: testId }, { $inc: { ... } }, function (err, response) {
...
});
但是很难进入阵列和另一个阵列。谢谢
解决方案
您可以使用$[] 位置运算符来更新嵌套数组。
router.put("/tests/:testId/:topicQuestionId/:choiceId", async (req, res) => {
const { testId, topicQuestionId, choiceId } = req.params;
const result = await Test.findByIdAndUpdate(
testId,
{
$inc: {
"topic.topicQuestion.$[i].choice.$[j].age": 1
}
},
{
arrayFilters: [{ "i._id": topicQuestionId }, { "j._id": choiceId }],
new: true
}
);
res.send(result);
});
假设我们有这个现有的文档:
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2116"),
"testName" : "Test 1",
"topic" : {
"topicTitle" : "Title",
"topicQuestion" : [
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf211a"),
"questionTitle" : "Question 1 Title",
"choice" : [
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf211c"),
"name" : "A",
"age" : 1
},
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf211b"),
"name" : "B",
"age" : 2
}
]
},
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2117"),
"questionTitle" : "Question 2 Title",
"choice" : [
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2119"),
"name" : "C",
"age" : 3
},
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2118"),
"name" : "D",
"age" : 4
}
]
}
]
},
"__v" : 0
}
如果我们想增加给定选择的值,我们使用这样的端点age
发送请求 ,其中PUT
http://.../tests/5e53e7d9bf65ac4f5cbf2116/5e53e7d9bf65ac4f5cbf211a/5e53e7d9bf65ac4f5cbf211b
"testId": "5e53e7d9bf65ac4f5cbf2116"
"topicQuestionId": "5e53e7d9bf65ac4f5cbf211a"
"choiceId": "5e53e7d9bf65ac4f5cbf211b"
推荐阅读
- spring-boot - 使用 Spring Cloud Vault 在 Spring Boot 应用程序中自动更新 AWS 凭证
- security - FreeRadius 结合漏洞扫描/软件状态检查
- proxy - 在 ews 自动生成的代理中设置 HttpHeader
- java - 不应在数组实例上调用“hashCode”和“toString”(SonarLint)
- r - R闪亮的依赖选择输入
- vba - 如何通过单独的函数更改 VBA 集合值
- reactjs - ReactJS 多选过滤器使用 OR 而不是 AND
- python - SysLogHandler 消息在远程服务器上分组在一行上
- image-processing - 3D 直方图的相似度度量
- typescript - Cypress+TS:从 HTMLelement 获取文本