问题描述
[
{
"_id": "5eb6c1d24298400b6eb6ca32","__v": 0
},{
"_id": "5efc7bb2b413a9524c7f3346","__v": 0
}
]
我想做的是基于城市ID,我想从我的实体模型(也有城市字段)中找到实体。 (因此可以根据城市对它们进行过滤)
为了让我的问题更清楚,如果我只有这样的json响应返回了城市
[
{
"_id": "5eb6c1d24298400b6eb6ca32","__v": 0
}
]
我这样做,然后就可以了。
if (person) {
const city = await City.find({ _id: person.cities });
const entity = await Entity.find({ cities: city[0]._id });
res.send(entity);
}
之所以有用,是因为在json响应中仅返回一个id,因此[0]起作用。
但是我如何针对多个城市ID(例如在第一个json响应中)执行此操作,然后将所有集体entity
归还?
解决方法
首先,创建一个城市ID数组,您需要为其获取实体并在$in
模型中应用Entity
过滤器。
const cities = await City.find({ _id: person.cities });
var cityIds = cities.map(city => city._id);
const entities = await Entity.find({
cities: {
$in : cityIds
}
});
console.log(entities); //logs the array of entities matching the cityIds