顺序化动态查询参数

jFr*_*cov 3 node.js express sequelize.js

req.query.p从前端MVC框架以JSON格式发送查询参数,关键是这可以是动态键和值,例如:

req.query.p = {nombre : 'juan'}
Run Code Online (Sandbox Code Playgroud)

要么

req.query.p = {pais : 'chile'}
Run Code Online (Sandbox Code Playgroud)

所以我需要键和值将它们放在where语句中,就像这样

exports.select = function(req, res){
    console.log('=> GET | Obtener peliculas'.bold.get);
        db.Pelicula
            .findAndCountAll({
                limit : req.query.limit,
                offset : req.query.offset,
                where : req.query.p ? [req.query.p.KEY + " = ?", req.query.p.VAL] : null
            })
            .success(function(resp){
                console.log(JSON.stringify(resp.rows, null, 4).bold.get);
                res.json({peliculas : resp.rows, meta : { total : resp.count}});
            });
}
Run Code Online (Sandbox Code Playgroud)

Jan*_*ier 5

where参数可以是一个对象,因此您只需传递 where: req.query.p