简体   繁体   English

无法从猫鼬的数组中删除元素

[英]Unable to remove element from Array in Mongoose

I am trying to remove an element through its _id from an array model in mongoose. 我试图从猫鼬的数组模型中通过其_id删除元素。 The same technique is working elsewhere in my code, but here it fails to remove the element. 相同的技术在我的代码的其他地方也起作用,但是在这里它无法删除该元素。 After hours of trying to change various parts of it, I am finally posting it here because maybe my lack of sleep is the main reason. 经过数小时的尝试来更改它的各个部分之后,我终于将其发布在这里,因为也许我睡眠不足是主要原因。 Can someone find out what i am doing wrong? 有人可以找出我做错了吗?

ABC.findOne({
    'user': new ObjectId(req.decoded._id),
    'activity.ride': new ObjectId(id)
}, {
    'activity.$': 1
}, function(err, doc) {

    if (doc !== null) {
        for (var j = 0; j < doc.activity.length; j++) {
            var request = JSON.parse(JSON.stringify(doc.activity[j]));
            doc.activity.remove(request._id);
            doc.save();
        }
    }
});

This is the model: 这是模型:

var activityItem = mongoose.Schema({
    timestampValue: Number,
    xabc: String,
    full: Boolean,
    comp: Boolean
});

var ABC = mongoose.Schema({
    activity: [activityItem],
    user: {
        type: mongoose.Schema.ObjectId,
        ref: 'User'
    },
    username: String
});

The $pull operator removes from an existing array all instances of a value or values that match a specified condition. $pull运算符从现有数组中删除一个或多个与指定条件匹配的值的所有实例。 And to remove element from array through findOneAndUpdate 并通过findOneAndUpdate从数组中删除元素

ABC.findOneAndUpdate({'user': new ObjectId(req.decoded._id)},
                    {$pull: {activity: {_id: request._id}}},
                    {new: true},
                    function(err, a) {
                        if (err)
                            console.log(err);
                        else
                            console.log(a);
                    });

BTW, I did not find ride in the activityItem schema, so I remove the ride from query condition. 顺便说一句,我没有在activityItem模式中找到ride ,因此我从查询条件中删除了ride设施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM