how to get object from array by value inside desired object by mongoose

Viewed 41

i have following bson data in mongoDB

{
 [
  {
     partyName : "p1",
     poNumber : "789",
  },
  {
     partyName : "p2",
     poNumber : "700",
  },
  {
     partyName : "p3",
     poNumber : "889",
  }
 ]
}

i want object from partyName for example if partyName is p1 then i want this

{
     partyName : "p1",
     poNumber : "789",
  }

i searched on the internet but not find relative result, all i found that query.elemMatch may help but i don't know how to use it please help me with the solution ( i want to use only mongoose )

1 Answers
await EntityName.findOne(
    { mainEntityName: { $elemMatch: { partyName: "p1" } } })

You can try this. Fill the EntityName and mainEntityName parts as your schema's names.

! Instead of "p1", add your parameter came from query.

To reach all elements which matched with your filter ; use find()

await EntityName.find(
    { mainEntityName: { $elemMatch: { partyName: "p1" } } })
Related