Mongo删除数组索引

3
我正在尝试从questions数组中删除特定的索引。我已经遵循了这两篇文章中的示例:

在MongoDb中,如何通过其索引删除数组元素

如何在MongoDB中删除数组的第n个元素

 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

在更新操作之前创建更新对象。您可以使用方括号表示法创建它,如下所示:

'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)    
    */
}

1
谢谢你,chridam,它像魔法一样奏效!我只需要在更新后加上一个=号。 - SpiritCode
@SpiritCode 不用担心,很高兴能帮忙 :) 漏掉了 = 是个打字错误,现在已经更正了。 - chridam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接