【问题标题】:Unable to update nested array in mongodb using nodeJs, and no error throwing无法使用 nodeJs 更新 mongodb 中的嵌套数组,并且没有错误抛出
【发布时间】:2018-07-07 20:04:10
【问题描述】:

我需要使用 nodejs 更新 mongodb 中的嵌套数组。我试过this,但没有帮助,甚至没有抛出错误。

我的收藏是这样的

{
    "country_details": [
    {
        "cities": [
            "Abbeville"
        ],
        "_id": "5a6ec189bb68bb09105eabe8",
        "countryCode": "US",
        "countryName": "United States"
    }
],
    "deletion_indicator": "N",
    "_id": "5a6ec189bb68bb09105eabe7",
    "date_created": "Mon Jan 29 2018 12:09:05 GMT+0530 (India Standard Time)",
    "__v": 0
}

我想更新城市,我已经尝试过了

let query = {_id: "5a6ec189bb68bb09105eabe7", countryCode: "US", countryName: "United States"};

countryAndCitiesModel.collection.update(
    query,
    {$push: {"country_details.$.cities": "ABC"}},

    (err, result)=> {
    if(err){
        return next(err);
    }else{
        return next(result);
    }
});

没有得到更新,但得到结果就像是

{
    "ok": 1,
    "nModified": 0,
    "n": 0
}

请帮忙..谢谢

【问题讨论】:

    标签: arrays node.js mongodb mongoose mongodb-query


    【解决方案1】:

    您正在尝试匹配 countryCodecountryName 嵌套对象 country_details 的属性,这就是您的查询无法匹配任何文档的原因。要解决这个问题,您应该修复字段的路径:

    db.collection.update(
        {_id: "5a6ec189bb68bb09105eabe7", "country_details.countryCode": "US", "country_details.countryName": "United States"},
        {$push: {"country_details.$.cities": "ABC"}})
    

    【讨论】:

    • 没用,兄弟
    • 再次相同的响应。
    • 兄弟,解决了我的问题,实际上我是直接使用集合而不是整个数据库,我的问题是我正在尝试类似 countryAndCitiesModel.collection.update,现在我已替换为 countryAndCitiesModel.update,跨度>
    猜你喜欢
    • 2015-03-04
    • 1970-01-01
    • 2018-10-22
    相关资源
    最近更新 更多