以下代码正常运行。但是,如何改善其速度,效率和时间复杂度
假设我在mongodb集合中有1000个国家,州和城市数据条目。我想通过匹配mongodb集合中的国家ID和州ID来检索所有城市数据。请告诉我完美的编码方式。
// @route GET citylist/:countryid/:stateid
// @desc get all the city from mongodb for countryid and stateid
router.get("/citylist/:countryid/:stateid", (req, res) => {
const isValidCountryid = mongoose.Types.ObjectId.isValid( req.params.countryid);
const isValidStateid = mongoose.Types.ObjectId.isValid(req.params.stateid);
if (isValidCountryid && isValidStateid) {
CityModel.find({
country_id: req.params.countryid,
state_id: req.params.stateid
})
.then(cities => {
if (!cities || !cities[0]) {
return res.status(404).json({ msg: "City not found" });
} else {
res.json(cities);
}
})
.catch(error => res.status(500).send(error));
} else {
res.json({ msg: "Country or State Id is not valid" });
}
});