【问题标题】:How to update(remove) a document in the nested array如何更新(删除)嵌套数组中的文档
【发布时间】:2013-09-03 15:08:22
【问题描述】:

我有一个用 mongoose 实现的 mongodb 测试架构。

var TestSchema = new mongoose.Schema({ exam:[ Exam ] });

var ExamSchema  = mongoose.Schema({type:String, questions: [  { question:{ type: ObjectId, ref: 'Question' }, answer:String } ]    });

var QuestionSchema = mongoose.Schema({ desciption:String, solution:String });

测试的想法是,一个学生可能会参加多个考试的考试,每个考试都有一个类型名称(可以是 Math 或 Physics )和一个问题列表 ObjectID 以及学生填写的相应答案。

此代码可以帮助在测试中为某些考试添加新问题和答案 TestModel.update({'_id':pid,'exam.type':type},{'$push':{'exam.$.questions':{'question':questionsId,'answer':answer}}} ,选项,功能(错误,参考){ 如果(错误){ console.log('将问题添加到考试'.red,err); 回调(错误,空); }别的{ console.log('向考试添加问题'.green+ref);
回调(空,参考); } }) 添加效果很好,但要删除问题和答案,更新不起作用。

Model.update({'_id':pid,'exam.type':type},{'$pull':{'exam.$.questions':questionId}},options,function(err,ref)

Model.update({'_id':pid,'exam.type':type},{'$pull':{'exam.$.questions.question':questionId}},options,function(err,ref)

Model.update({'_id':pid,'exam.type':type,'exam.questions.question':questionId},{'$pull':{'exam.$.questions.$.question':questionId}},options,function(err,ref)

Model.update({'_id':pid,'exam.type':type,'exam.questions.question':questionId},{'$pull':{'exam.questions.$.question':questionId}},options,function(err,ref)

我尝试了这些方法,但这些方法都不起作用

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在下一个修饰符中使用 $ 运算符:

    {'$pull': {'exam.$.questions': questionId}
    

    您必须首先在查询中使用 $elemMatch: 运算符:

    {'_id': pid, exam: { $elemMatch: {type: type} } }
    

    【讨论】:

      【解决方案2】:

      其他人可能会提供一个 mongo 语法答案。

      我喜欢流星的一个方面是你可以在任何地方使用 javascript/coffeescript。我谦虚地建议您将该策略扩展到您对 mongo 更新的使用。我发现自己只是直接使用我的 json/object 操作能力并 $set 整个事情,而不是学习另一种语法。有人会说,在证明它会产生影响之前限制您检索的字段是过早的优化,因此您可能无论如何都要检索数据。

      【讨论】:

        猜你喜欢
        • 2018-07-24
        • 1970-01-01
        • 2017-06-05
        • 2015-07-13
        • 2012-05-18
        • 1970-01-01
        • 2023-03-18
        相关资源
        最近更新 更多