简体   繁体   English

数组中包含 objectID 的搜索字段

[英]Search field with objectID inside an array

I have an array of objectid stored inside a field called linkedAccounts like this:我有一个 objectid 数组存储在一个名为linkedAccounts的字段中,如下所示:

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

when I do console.log of accountId , I get:当我执行accountIdconsole.log时,我得到:

new ObjectId("639f131640e86ede985400aa").

I want to find a specific object inside linkedAccount that matches with req.params.accountId我想在linkedAccount中找到与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的特定文档。

review.linkedAccount.find((c) => c.accountId === (new ObjectId(req.params.accountId));

You can use $ projection, which will return a matching object in array,您可以使用$ projection,它将返回数组中的匹配对象,

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

Playground操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM