1

I need to update nested array in mongodb using nodejs. I have tried like this but not helped and even its not throwing error.

My Collection is 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
}

and I want to update cities, And I have try like one

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);
    }
});

not getting update, but getting result like is

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

Please help.. Thanks

enter image description here

1 Answer 1

2

You're trying to match countryCode and countryName which are properties of nested object country_details and that's why your query can't match any document. To fix that you should fix paths to your fields:

db.collection.update(
    {_id: "5a6ec189bb68bb09105eabe7", "country_details.countryCode": "US", "country_details.countryName": "United States"},
    {$push: {"country_details.$.cities": "ABC"}})
Sign up to request clarification or add additional context in comments.

3 Comments

Not helped, bro
again same response.
Bro, solved my issue, actually I am directly using the collection instead of whole db, my issue is i am trying like countryAndCitiesModel.collection.update, now i have replaced with countryAndCitiesModel.update,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.