Harsh Patel
Harsh Patel

Reputation: 6830

Match one field and ignore others

I have my data like this:

  {"_id":"5c0a17013d8ca91bf4ee7885",
    "ep1":{
        "email":"[email protected]",
        "password":"123456",
        "phoneNo":"123456789",
        "endpointId":"ep1"
        }
  }

I want to match all the object that has key ep1 and value "email":"[email protected]" and set ep1:{}

Code:

My req object is like this {"endpointId":"ep1", "email": "[email protected]"}

    let query = {[req.body.endpointId]:{email: req.body.email}};
        endpointModelData.endpoint.updateMany(query, {[req.body.endpointId]:{}}, {multi: true}, function(err, doc){
            if (err) return res.send(500, { error: err });
            console.log(doc)
            return res.status(201).send("success.");
        })

But this code only works if there is only one entry(that is email) inside my ep1 object

like this:

{"_id":"5c0a17013d8ca91bf4ee7885",
    "ep1":{
        "email":"[email protected]"
        }
  }

So, how can I match email and ignore other fields?

Upvotes: 0

Views: 43

Answers (1)

Akrion
Akrion

Reputation: 18525

You need to match: {"ep1.email":"[email protected]"} so change your query to:

let query = { [`${req.body.endpointId}.email`]: req.body.email };

You can see that filter working here

On the end of the day your update should look like:

updateMany({ "ep1.email" : "[email protected]" }, { "ep1": {} }, {multi: true})

Upvotes: 2

Related Questions