【问题标题】:Removing an element from an array of subdocuments by subdocumentId通过 subdocumentId 从子文档数组中删除一个元素
【发布时间】:2015-04-17 21:23:16
【问题描述】:

所以我有以下架构:

var questionsSchema = new Schema({
        nr: Number,
        points: Number,
        description: String,
        groups: [{
            type: Schema.Types.ObjectId,
            ref: 'Group',
            default: []
        }],
        createdOn: {type: Date, default: Date.now()},
        isActive: {type: Boolean, default: true}
    });

var roundSchema = new Schema({
        name: String,
        index: Number,
        questions: [ questionsSchema ]
    });

现在我有一个操作来删除一个问题(问题是唯一的),而不需要轮(父)_id。

我查看了here 关于如何从数组中提取元素的信息,但是我根本找不到正确的方法,在链接中它是一个非文档数组,所以这有点不同我的情况。

我尝试过的:

function removeQuestionById(req, res) {
        Round.update({"questions._id": req.params.id}, {$pull: {"questions._id": req.params.id}}, function(err, rowsAffected){
            if(err){
                res.sendStatus(500);
                return console.log("An error occured when trying to remove a question!", err);
            }
            console.log("Amount of rows affected was " + rowsAffected);
            return res.end();
        })
    }

没有用,所以我假设我只需要在更新语句中指定子文档的字段:

function removeQuestionById(req, res) {
        Round.update({"questions._id": req.params.id}, {$pull: {"_id": req.params.id}}, function(err, rowsAffected){
            if(err){
                res.sendStatus(500);
                return console.log("An error occured when trying to remove a question!", err);
            }
            console.log("Amount of rows affected was " + rowsAffected);
            return res.end();
        })
    }

也没有工作,我在这两种情况下受影响的行数都是 0。 在过去的几个小时里,我尝试了其他几件事,但都没有奏效。

注意:请求对象中的问题_id是正确的。

【问题讨论】:

    标签: arrays mongodb mongoose subdocument


    【解决方案1】:

    我终于让它工作了,但是我确实需要父 _id 来执行此操作:

    Round.update({"_id": req.params.roundId}, {$pull: {"questions": {"_id": req.params.questionId}}},function cb(err) {
                if(err){
                    res.sendStatus(500);
                    return console.log("An error occured when trying to remove a question!", err);
                }
                return res.end();
            });
    

    如果有人知道不需要 parentId 的方法,请告诉。

    编辑:找到它,只需将 _id 替换为 questions._id 并关闭正确的参数值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 2020-10-21
      • 2020-07-20
      • 1970-01-01
      • 2021-07-02
      • 2016-10-25
      • 2013-05-27
      相关资源
      最近更新 更多