我正在努力更新mongoDB中嵌套arrray中的元素。
假设我有这个架构:
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: [
{
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
}
]
},
{
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
}
]
}
]
}
当测试版本为:1A使用mongooseJS时,如何向数学类别添加新问题?
答案 0 :(得分:0)
db.test.update(
{
category: 'Math',
'tests.version': '1A'
},
{
$push: {
'tests.$.questions': {
problem: 'test',
multiplechoices: ['a', 'b', 'c'],
correctAnswer: 1
}
}
}
答案 1 :(得分:0)
试试这个..
Test.findOne( {category:"Math", tests.version:"1A"}, function(err, result){
if (!err && result) {
result.tests.questions.push({"new question"}); //push ur new question
var test = new Test(result); //this is ur mongoose mdel
test.save(function(err, result2){ //update
if(!err) {
console.log(result2); //updated result
} console.log(err);
})
} else console.log(err);
});