I have an array of MongoDB Ids like this:
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 = [
{
"_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 中使用 mongodb 的 $in 运算符
const storedNetworks = await Network.find({"_id":{"$in":networks}});
You should to use $in
operator. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.