Mongo / Express:如果未传递查询参数,如何返回集合中的所有文档?

时间:2019-05-18 02:16:47

标签: node.js mongodb express mongoose request

如果没有传递任何查询参数,我将尝试从Mongo集合返回所有文档。目前,我有3个可选的查询参数,可由用户传递。

localhost:3000/api/projects

//should return all projects. Currently this is returning []
localhost:3000/api/projects?id=1

//should return projects with id of "1". Working properly.
localhost:3000/api/projects?name=myproject

//should return projects with name of "myproject". Working properly.
localhost:3000/api/projects?created_by=John

//should return projects created by "John". Working properly.

在我的路线内,我正在尝试确定我的请求是否包含任何查询值。如果没有,那么我想返回集合中的所有文档。如上所述,这不会返回任何内容。

router.get('/', async (req, res) => {
    if (req.query !== '') {
        const project = await Projects.find({
            $or: [
                { _id: req.query.id },
                { name: req.query.name },
                { created_by: req.query.created_by }]
        });
        res.json(project);
    }
    else {
        const project = await Projects.find();
        res.json(project);
    }
});

3 个答案:

答案 0 :(得分:1)

请尝试以下操作:

router.get('/', async (req, res) => {
        let searchQuery = {}

        if(req.query.id){
            searchQuery._id = req.query.id
        }

        if(req.query.name){
            searchQuery.name = req.query.name
        }

        if(req.query.created_by){
            searchQuery.created_by = req.query.created_by
        }

        const project = await Projects.find(searchQuery);
        res.json(project);
});

答案 1 :(得分:0)

您可以这样编写api处理程序:

router.get('/', async (req, res)=>{
  let options = {...req.query};
  try{
    const project = await Projects.find(options);
    res.json(project);
  }catch(e){
    console.log(e);
  }

});

这将根据您的查询获取文档。如果没有查询参数,则req.query将为空对象,因此将查找所有文档。 希望这会有所帮助!

答案 2 :(得分:0)

router.get('/', async (req, res) => {

const id = req.query.id || null;
const name = req.query.name || null;
const created_by = req.query.created_by || null;

const query = { id, name, created_by };
const project = await Projects.find(query);
res.json(project); 
});

我没有测试它,但是我会用这种方式解决您的问题。