简体   繁体   English

如何从 NodeJs/express/mongoose 中的对象中删除项目?

[英]How can I delete an item from an Object in NodeJs/express/mongoose?

I know this has been asked before, but no one of the answers worked for me.我知道以前有人问过这个问题,但没有一个答案对我有用。 In my App, I have a users collection in MongoDb.在我的应用程序中,我在 MongoDb 中有一个用户集合。 These users collection have an array field named 'segActuacions' that can be modified within a form.这些用户集合有一个名为“segActuacions”的数组字段,可以在表单中修改。 This form sends this Object to router:此表单将此对象发送到路由器:

{
    "segActuacions.0.date": "27/09/2016",
    "segActuacions.0.body": "first item",
    "segActuacions.1.date": "27/09/2016",
    "segActuacions.1.body": "second item"
}

router has this line to go to controller:路由器有这条线去控制器:

router.delete('/seg_act_upd_EE/:id/actDel/:i', 
    sessionController.loginRequired,  
    userController.actuaDelete
);

where ':id' is User-id , and ':i' is the index of segActuacions其中':id'User-id ,而':i'segActuacions的索引

Controller has this code:控制器有这个代码:

exports.actuaDelete = function (req, res) {
    var userId = req.params.id;
    var userI = req.params.i;
    var usr = req.body;

    delete usr['segActuacions.userI.date'];
    delete usr['segActuacions.userI.body'];

    models.User.findByIdAndUpdate(userId, usr, function (error, user){
        if (error) res.json(error);
        res.redirect('/list_EE');
    });
}

I want to delete the fields 'i' of the Object (for instance: if i=0 , i'd like to delete "segActuacions.0.date" and "segActuacions.0.body" , ...but nothing happens.我想删除对象的字段'i' (例如: if i=0 ,我想删除"segActuacions.0.date""segActuacions.0.body" ,...但没有任何反应。

If you are simply looking to delete the keys from the req.body object and subsequently update your collection with the remaining keys then follow this example:如果您只是想从req.body对象中删除键,然后使用剩余的键更新您的集合,请按照以下示例操作:

exports.actuaDelete = function (req, res) {
    var userId = req.params.id;
    var userI = req.params.i;
    var usr = req.body;

    delete usr["segActuacions."+ userI +".date"];
    delete usr["segActuacions."+ userI +".body"];

    models.User.findByIdAndUpdate(userId, usr, function (error, user){
        if (error) res.json(error);
        res.redirect('/list_EE');
    });
}

To remove the fields from the collection, the best way is to use $unset operator because delete removes the keys from an object and updating the collection with the updated object will not remove the actual fields from the collection.要从集合中删除字段,最好的方法是使用$unset运算符,因为delete会从对象中删除键,并且使用更新的对象更新集合不会从集合中删除实际的字段。

In essence you use the dot notation to correctly identify the field to remove.本质上,您使用点符号来正确识别要删除的字段。 For example, you would want to achieve the following mongo shell update operation:例如,您希望实现以下 mongo shell 更新操作:

db.users.update(
    { "_id" : userId },
    {
        "$unset": {
            "segActuacions.1.date" : "",
            "segActuacions.1.body" : ""        
        }
    }
)

This will remove the fields from the element in position with index 1 in the segActuacions array.这将从segActuacions数组中索引为 1 的元素中删除字段。

Tying all this with your controller method, you can construct an update object that is similar to将所有这些与您的控制器方法联系起来,您可以构造一个类似于

{
    "$unset": {
        "segActuacions.1.date" : "",
        "segActuacions.1.body" : ""        
    }
}

such as

exports.actuaDelete = function (req, res) {
    var userId = req.params.id;
    var userI = req.params.i;
    var usr = {};

    usr["segActuacions."+ userI +".date"] = "";
    usr["segActuacions."+ userI +".body"] = "";

    models.User.findByIdAndUpdate(userId, { "$unset": usr }, function (error, user){
        if (error) res.json(error);
        res.redirect('/list_EE');
    });
}

Note your delete wouldn't work because you are using userI as a string and not using the variable value.请注意,您的删除不起作用,因为您使用userI作为字符串而不是使用变量值。 Also update will just update the fields that are in the object.更新也只会更新对象中的字段。

But I think you should use $unset , like the following:但我认为您应该使用$unset ,如下所示:

var updateObj = {};
updateObj['segActuacions'] = {};
updateObj['segActuacions'][userI] = {};
updateObj['segActuacions'][userI]['body'] = '';
updateObj['segActuacions'][userI]['date'] = '';

var update = { $unset:  updateObj };

models.User.findByIdAndUpdate(userId, update, function (error, user){
    if (error) res.json(error);
    res.redirect('/list_EE');
});

(This code can be improved and wasn't tested) (此代码可以改进,未经测试)

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

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