Node.js NodeJS中数组的数组中的Mongoose更新值
我的测试模式:Node.js NodeJS中数组的数组中的Mongoose更新值,node.js,mongodb,mongoose,mongoose-schema,Node.js,Mongodb,Mongoose,Mongoose Schema,我的测试模式: var TestSchema = new Schema({ testName: String, topic: { topicTitle: String, topicQuestion: [ { questionTitle: String, choice: [ {
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的age$incvalue
我可以有测试id、主题问题id和选择id
如何在NodeJS中的mongoose中编写此查询
通常,我使用以下查询来更新值:
Test.findOneAndUpdate({ _id: testId }, { $inc: { ... } }, function (err, response) {
...
});
但是很难进入一个数组和多个数组。谢谢您需要告知您想要什么选择,并且在更新部分,您需要更改您的操作方式 例如:
Test.findOneAndUpdate({ _id: testId, topicQuestion.choice._id: choiceId}, { 'topicQuestion.$.choice': {$inc: { age: <numberToIncrement> }}}, {new: true}, function (err, response) {
...
});
可以使用更新嵌套数组
router.put/tests/:testId/:topicQuestionId/:choiceId,异步请求,res=>{
const{testId,topicQuestionId,choiceId}=req.params;
const result=await Test.findByIdAndUpdate
睾丸,
{
$inc:{
topic.topicQuestion.$[i].选择.$[j].年龄:1
}
},
{
数组过滤器:[{i.\U id:topicQuestionId},{j.\U id:choiceId}],
新:真的
}
;
res.sendresult;
};
假设我们有这个现有的文档:
{
"_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
}
若我们想增加一个给定选择的年龄值,我们将使用如下端点发送一个PUT请求http://.../tests/5e53e7d9bf65ac4f5cbf2116/5e53e7d9bf65ac4f5cbf211a/5e53e7d9bf65ac4f5cbf211b 在哪里
测试代码:5e53e7d9bf65ac4f5cbf2116
主题问题ID:5e53e7d9bf65ac4f5cbf211a
choiceId:5e53e7d9bf65ac4f5cbf211b谢谢您的回复,但我的回复为空,年龄没有更新。Test.findOneAndUpdate{u-id:testId,'topicQuestion.choice.'u-id':choiceId},{'topicQuestion.$.choice':{$inc:{age:1}}},{new:true},函数err,响应{你是否通过了choiceId而不是通过了testId?也可以这样尝试:[…]{$inc topicQuestion.$.choice.$.age:{1},{new:true}[…]