3

I have an array of objectid stored inside a field called linkedAccounts like this:

linkedAccount : [
  {accountId:639f131640e86ede985400aa, comments:[]}, 
  {accountId:639f131qwqwqe86ede985400aa, comments:[]}, 
  {accountId:639f131640e86ede985400aa, comments:[]}
]

when I do console.log of accountId, I get:

new ObjectId("639f131640e86ede985400aa").

I want to find a specific object inside linkedAccount that matches with req.params.accountId

I wrote this line but it's not working. Here review is a specific document inside which I have linkedAccount.

review.linkedAccount.find((c) => c.accountId === (new ObjectId(req.params.accountId));
Newbie_developer
  • 233
  • 1
  • 12

1 Answers1

0

You can use $ projection, which will return a matching object in array,

let r = review.find({
  "linkedAccount.accountId": ObjectId(req.params.accountId)
},
{
  "linkedAccount.$": 1
})

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59