简体   繁体   English

Mongoose 查找与 id 数组的每个条目匹配的所有文档

[英]Mongoose find all documents which matches every entries of an array of ids

I have an array of MongoDB Ids like this:我有一个像这样的 MongoDB Id 数组:

networks = ["5e1cfabb61e9314617fe2db5", "5e1cfbbbe519704860d9a720", "5e1cfbdd4ab5514888b4c6eb"]

I need to push in a new array all documents (the full object) from my database that matches every entry of networks array.我需要从我的数据库中推入一个新数组,所有文档(完整对象)与网络数组的每个条目相匹配。

So I want a new like, lets say peopleNetworks to be like this:所以我想要一个新的喜欢,让我们说 peopleNetworks 是这样的:

`peopleNetworks = [
  {
    "_id": "5e1cfabb61e9314617fe2db5",
    "name": "Facebook",
    "createdAt": "2020-01-13T23:18:19.593Z",
    "updatedAt": "2020-01-13T23:18:19.593Z",
    "__v": 0
  },
  {
    "_id": "5e1cfbbbe519704860d9a720",
    "name": "Instagram",
    "createdAt": "2020-01-13T23:22:35.057Z",
    "updatedAt": "2020-01-13T23:22:35.057Z",
    "__v": 0
  },
  {
    "_id": "5e1cfbdd4ab5514888b4c6eb",
    "name": "Vero",
    "createdAt": "2020-01-13T23:23:09.501Z",
    "updatedAt": "2020-01-14T00:00:05.458Z",
    "__v": 0
  }
]`

I tried to filter my collection using the networks array like this:我尝试使用网络数组过滤我的收藏,如下所示:

`const peopleNetworks = [];
 const storedNetworks = await Network.find();
 storedNetworks.filter(network => { networks.forEach(id => 
  {
   if (id === network._id) peopleNetworks.push(network);
  })
 );`

But it doesn't work.但它不起作用。

I think the proper way to do this is by chaining the filter after .find() but I messed up when I tried.我认为正确的方法是在 .find() 之后链接过滤器,但我尝试时搞砸了。

您可以在 find 中使用 mongodb 的 $in 运算符

const storedNetworks = await Network.find({"_id":{"$in":networks}});

You should to use $in operator.您应该使用$in运算符。 Something like就像是

await Network.find({ _id: { $in: networks } });

This should return you the desired documents and you don't have to fetch all and then filter这应该会返回您想要的文档,您不必全部获取然后过滤

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

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