Expressjs: Search query api

后端 未结 1 1745
盖世英雄少女心
盖世英雄少女心 2021-02-10 06:19

I want to search through my user repository with a query string.

This should return all users with a similar username \"kyogron\" and similar email \"kyogron@gmail\"

1条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-10 06:57

    app.get('/users', function(req, res) {
        var query = User.find({});
    
        Object.keys(req.query).forEach(function(key) {
            query.where(key).regex(new RegExp(req.query[key]));
        });
    
        /*
        if (req.query.username) {
            query.where('username').regex(new RegExp(req.query.username));
        }
        if (req.query.email) {
            query.where('email').regex(new RegExp(req.query.email));
        }*/
    
        query.select('username', 'email');
        query.exec(function(err, users) {
            if (err) throw err;
            res.json(users);
        });
    
    });
    

    The first didn't work because I had a typo (.select() not .where()). The second was found in an extra thread

    I am still a bit unsure about the chosen approach.

    Iterating req.query would allow to make the code reusable (maybe as precondition routing parameter-function) but it is quite susceptible for errors

    0 讨论(0)
提交回复
热议问题