fernando fincatti
fernando fincatti

Reputation: 319

How to update a subdocument in mongoose?

I have a problem while using update in mongoose. I have one collection that looks like this:

{
    "client": "XXXXX",
    "counts": [
        {
            "bank": "XXXXX",
            "agency": "XXXXX",
            "count": "XXXXX",
            "value": "XXXXX",
        },

        {
            "bank": "XXXXX",
            "agency": "XXXXX",
            "count": "XXXXX",
            "value": "XXXXX",
        }
    ]
}

What I would like to do is to update the key "value" of a client's count matching by the bank and the agency.

I tried this:

model.find({
    "client": "XXXXX",
    "counts": {
      "$elemMatch": {
        "bank": "bank name",
        "count": "count number"
      }
    }
})

but nothing happens. Someone can help me, please?

Upvotes: 0

Views: 36

Answers (1)

Mohammad Yaser Ahmadi
Mohammad Yaser Ahmadi

Reputation: 5051

for updating you should use update or updateOne or findOneAndUpdate functions, but you use find(), change it


const filter = { name: 'Jean-Luc Picard' };
const update = { age: 59 };

// `doc` is the document _before_ `update` was applied
let doc = await Character.findOneAndUpdate(filter, update);

check the $elemMatch in update if you want update array

Upvotes: 1

Related Questions