javascript - 如何通过express js过滤动态对象
问题描述
我正在为 REST api 使用 express,我想通过 req.query 对我的帖子进行一些过滤,在帖子结构中我使用它调用选项的动态对象,它是我的帖子结构:
{
"category": [
{
"id": 2,
"name": "mashin"
},
{
"id": 102,
"name": "savari"
}
],
"_id": "5eb52dc8e2838431703942eb",
"user": "5deea38cfc84f42590e01942",
"title": "qazwsx",
"description": "qazwsx",
"options": {
"price": "100"
},
"phone": "",
"date": "2020-05-08T10:00:40.626Z",
"__v": 0
},
{
"category": [
{
"id": 2,
"name": "mashin"
},
{
"id": 102,
"name": "savari"
}
],
"_id": "5eb52db6e2838431703942ea",
"user": "5deea38cfc84f42590e01942",
"title": "xswzaq",
"description": "qazwsx",
"options": {
"transaction_type": "",
},
"phone": "",
"date": "2020-05-08T10:00:22.783Z",
"__v": 0
},
如您所见,有些帖子有价格,而另一些则没有。对于后端过滤器,我使用以下代码:
router.get('/', async (req, res) => {
try {
const posts = await Post.find().sort({ date: -1 });
let response = [];
const q = {} // Query object
if (req.query.city) { q.city = req.query.city }
if (req.query.title) { q.title = req.query.title }
if (Object.keys(q).length === 0) {
// NO query parameters, send it all...
response = posts;
} else {
// We have a query, filter response to match request
response = posts.filter(post => {
return Object.keys(q).every((key) => post[key] === q[key]);
}, q);
}
// Filter by Price
if (req.query.PriceFrom) {
response.filter(post => {
if (typeof (post.options.price) !== 'undefined') {
console.log('p' + post.options)
}
else {
console.log('n' + post.options)
}
})
}
// de-duplication:
response = _.uniqBy(response, 'id');
const resultPosts = response.slice(req.query.start, req.query.count)
res.json(resultPosts);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error!');
}
});
在 console.log 我收到这个错误:
[0] { price: '100' }
[0] Cannot read property 'price' of undefined
[0] { transaction_type: '', price: '100' }
[0] { transaction_type: '200', price: '200' }
[0] { transaction_type: '1', price: '100' }
你有解决方案或想法吗?
解决方案
问题是您试图访问未定义的.price
位置。post.options
所以添加这个,它应该捕获 undefinedpost.options
而不会引发错误。
if (post.options && typeof (post.options.price) !== 'undefined') {}
推荐阅读
- swift - 我真的不知道为什么我的 collectionViewCell 消失了
- r - Tidyverse 按行绑定未命名向量列表的方法 - do.call(rbind,x) 等效
- javascript - 使用 react-native-background-timer 实现计时器,标识符“秒”已被声明
- sql - 存储过程是否总是完成运行?
- reactjs - 如何在反应js中隐藏和显示一个div
- rest - 如何确定 REST url 在 Delphi REST 服务器中是否包含 HTTPS?
- maximo-anywhere - IBM Maximo Anywhere 中的路由工作流
- python - Pandas,Geopandas.- 空间连接操作
- typo3 - TYPO3 9.5 LTS - 使用 routeEnhancers 配置自定义 PAGE 类型
- mysql - 为什么 MySQL 在没有 group by 语句的情况下给我一些聚合函数的结果