findOneAndUpdate() a sub-array based on conditions in find query

Viewed 121

The Tag schema structure is as follows:

_id: "abcsd12312",
nsp: "localhost.com",
tags: [
    0: { tag: "#feedback",
         agent_list: [
                  0: { email : "murtaza@local.com", count: 0},
                  1: { email: "abc@gmail.com", count: 0}
         ]
       },
    1: { tag: "#spam",
         agent_list: [
                  0: { email: "abc@live.com", count: 0},
                  1: { email: "murtaza@local.com", count: 1}
          ]
        }
     ]  

I have two parameters that comes from a source and falls into a function which i have made, the parameter are tag_name and agent_email, their values can be "#feedback" and "murtaza@local.com" as an example.

I have to iterate through the tags collection based on the given tag_name and then if record is found then iterate through its agent_list which equals to the value of parameter 'agent_email'. Then i have to increment its 'count' by 1.

I have a following function:

public static async UpdateAgentTicketCount(agent_email: string, tag_name: string, nsp: string) {
    try {
        console.log(agent_email, tag_name, nsp);
        return this.collection.findOneAndUpdate({nsp: nsp, tags: {$elemMatch: {tag: tag_name}}}, {});
    } catch (error) {
        console.log(error);
    }
}

I need a mongodb query to increment this count by 1, I am using mongodb in my angular code and have a function which performs this task, what ever query will be provided i will write this query inside my function.

1 Answers

Try this,

public static async UpdateAgentTicketCount(agent_email: string, tag_name: string, nsp: string) {
    try {
        console.log(agent_email, tag_name, nsp);
        for(let t of this.collection.tags){
            if(t.tag==tag_name){
                t.agent_list.find(agent => agent.email==agent_email).count = t.agent_list.find(agent => agent.email==agent_email).count + 1;
            }
        }
        return this.collection;
    } catch (error) {
        console.log(error);
    }
}
Related