续集动态查询参数

时间:2014-09-29 18:10:50

标签: node.js express sequelize.js

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

req.query.p = {nombre : 'juan'}

req.query.p = {pais : 'chile'}

所以我需要键,以及将它们放在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}});
            });
}

3 个答案:

答案 0 :(得分:5)

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

即可

答案 1 :(得分:0)

通常,我放置整个对象,因此,如果它为空,它将正常工作,就好像没有条件WHERE。 您不需要在where中添加{},因为来自req.query的对象已经有了它。

const filter = req.query;
example= await ModelExample.findAndCountAll({
               where:
                filter
})

答案 2 :(得分:0)

使用 ES6 并使用动态属性,我会这样做

const { Op } = require("sequelize");

const from = new Date()
// const to = new Date().setMinutes(40)
const to = null

let where = {
    timestamp: {
        [Op.or]: {}
    }
}

if (from) {
    where.timestamp[Op.or][Op.gte] = new Date(from)
}
if (to) {
    where.timestamp[Op.or][Op.lte] = new Date(to)
}
console.log(where);

Model.find({ where })
相关问题