Mongo删除数组索引

时间:2016-03-09 15:45:22

标签: mongodb

我正在尝试从问题数组中删除特定索引。我已经按照这两个帖子中的示例进行了操作:

In mongoDb, how do you remove an array element by its index

How to delete n-th element of array in mongodb

 var quiz =  {
                        quizName: "",
                        createdBy: "",
                        theme: "",
                        isPrivate: "",
                        expiringDate: "",
                        createdOn: "",
                        questions:[
                                   {question: "",
                                   index: "",
                                   answers: [
                                             answer: "",
                                             radioCorrect: "",
                                             index: ""
                                   ]},{
                                   question: "",
                                   index: "",
                                   answers: [
                                             answer: "",
                                             radioCorrect: "",
                                             index: ""
                                   ]}

                        ]

这给了我一个未指定的错误。我尝试过类似的变体。

'deleteQuiz': function(quizId, index1){ 


    Quizes.update({_id: quizId},{ $unset : {questions.index1: 1}})

    Quizes.update({_id: quizId},{ "$pull" : {"questions": null}}) }

1 个答案:

答案 0 :(得分:0)

在更新操作中使用之前创建更新对象。您可以使用square bracket notation创建它,如下所示:

'deleteQuiz': function(quizId, index1){ 
    var query = {"_id": quizId},
        update { "$unset": { } };

    update["$unset"]["questions."+index1] = 1;
    Quizes.update(query, update)

    /* or if using the $pull operator
    var query = {"_id": quizId},
        update = { "$pull": { } };

    update["$pull"]["questions."+index1] = null;
    Quizes.update(query, update)    
    */
}