如何在express js中使用特定字段而不是id进行查询 [英] how to query using a specific field instead of id in express js

查看:25
本文介绍了如何在express js中使用特定字段而不是id进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我按城市查询搜索的代码.我在我的帖子中找不到> 我需要能够搜索特定城市并获取与该城市匹配的字段的所有记录.例如,如果城市是市中心,我想要所有城市的记录

Below is my code to query search by city. I am getting not found in my post> I need to be able to search for a specific city and get all the records for the field that matches the city. For example, if city is Downtown, I want all the records with the city downtown

            router.get("/search", (req, res, next) =>{
            const city = req.query.city;
            Facility.findAll(city)
                .select('name type mobile price streetName city state _id')
                .exec()
                .then(docs => {
                console.log("From database", docs);
                if (docs) {
                    res.status(200).json({
                        facility: docs
                    });
                } else {
                    res
                    .status(404)
                    .json({ message: "No valid entry found for provided City" });
                }
                })
                .catch(err => {
                console.log(err);
                res.status(500).json({ error: err });
                });

            });

推荐答案

以下是工作代码:

router.get('/search', (req, res) => {
const city = req.query.city
    Facility.find({city})
        .select('name type mobile price streetName city state')
            .exec((err, docs) => {
                if (err) {
                    return res.status(500)
                    .json({ message: 'error querying cities', error: err });
                }
                if (!docs) {
                    return res.status(404)
                    .json({ message: 'No valid entry found for provided City' });
                }
                return res.status(200)
                    .json({
                    count: docs.length,
                    facility: docs
                });
            })

});

这篇关于如何在express js中使用特定字段而不是id进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆