【问题标题】:Remove element from array in mongoose从猫鼬中的数组中删除元素
【发布时间】:2018-05-28 15:48:29
【问题描述】:

我正在研究 nodejs/express

我想在 mongoose 中删除数组中的元素

我有这种格式的文件

{ 
    "_id" : ObjectId("5a2e19223e50551504b316c0"), 
    "username" : "nikhil", 
    "email" : "nikhil@itradicals.com", 
    "password" : "$2a$10$f3NvrTywIezlzKcZLWSU0O98gn6Mc.Q8B0ZNEDG2F66f4rwyo65Yu", 
    "companyname" : "itr", 
    "role" : "vendor", 
    "verify" : "true", 
    "createddate" : ISODate("2017-12-10T18:30:00.000+0000"), 
    "account" : [
        {
            "Region" : [
                "North America", 
                "Africa", 
                "Asia"
            ]
        }, 
        {
            "Category" : [
                "Group 1", 
                "Group 2", 
                "Group 3"
            ]
        }
    ]
}

我想使用我得到的 mongoose 查询仅删除 Region 字段 动态数据,因此用户可以删除任何数组,无论是区域还是 类别。我正在获取要在参数中删除的数组名称 “场地”。

module.exports.setupAccount = function(id,field,callback){
        var query = { _id: id};
        User.findOneAndUpdate(query,{ $set: { account.Region:[] }}, callback);
}

我是 nodejs 和 mongoose 的新手 提前致谢

【问题讨论】:

    标签: arrays json node.js mongodb mongoose


    【解决方案1】:

    如果您不想在删除字段后保留空文档,您可以简单地 $pull 数组中的整个元素:

    module.exports.setupAccount = function(id,field,callback){
        var query = { _id: id };
        User.findOneAndUpdate(query, { $pull: { "account": { field: { $exists: true } } } }, callback);
    }
    

    【讨论】:

    • 我用这个和那个帮助我解决我的问题领域是动态的,所以我需要在括号中使用它。
    • 使用 [field] 为我做。
    【解决方案2】:

    您可以使用以下功能。

    使用计算属性名称将字段动态传递给未设置和查询表达式。

    查询以验证数组是否存在,然后通过$unset 删除数组。

    $ 位置运算符根据查询条件动态定位数组。如果您知道数组位置,则可以对数组索引进行硬编码。

    module.exports.setupAccount = function(id, field, callback){
       var query = { "_id": id, ['account.' + field]:{"$exists":true}};
       var unset = {"$unset":{['account.$.' + field]:""}};
       User.findOneAndUpdate(query, unset, callback);
    }
    

    【讨论】:

    • 感谢您的帮助,但它留下了空文档。我不需要空文档
    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 2021-06-14
    • 2022-08-02
    • 2013-01-23
    • 2020-12-18
    • 1970-01-01
    • 2018-06-11
    • 2020-12-31
    相关资源
    最近更新 更多