为mongodb REST API编写通用查询函数

时间:2014-10-14 18:11:49

标签: javascript node.js mongodb rest mongoose

我正在使用node.js表示MongoDB和Mongoose为我的应用程序创建rest api。我想知道有什么类型的代码可以替换下面这样的代码来更通用吗?我不想一直通过所有参数,但只是在一定时间内。大多数时候我只想传递其中的一部分。通常在Java中,我为这些东西创建构建器,但我不知道Javascript的任何技巧:)

exports.getMessages = function (req, res) {

    var from = req.query.from;
    var deleted = req.query.deleted;
    var readed = req.query.readed;

    if(from && deleted && readed) {
        Message.find({to: req.user.email, from: from, deleted: deleted, readed: readed}, function(err, messages) {
            if(err) {
                res.send(err);
            }
            res.json(messages);
        })
    } else if(from && deleted) {
        Message.find({to: req.user.email, from: from, deleted: deleted}, function(err, messages) {
            if(err) {
                res.send(err);
            }
            res.json(messages);
        })
    } else if (from && readed) {
        Message.find({to: req.user.email, from: from, readed: readed}, function (err, messages) {
            if(err) {
                res.send(err);
            }
            res.json(messages);
        });
    } else if(deleted && readed) {
        Message.find({to: req.user.email, deleted: deleted, readed: readed}, function (err, messages) {
            if(err) {
                res.send(err);
            }
            res.json(messages);
        });
    } else if(deleted){
        Message.find({to: req.user.email, deleted: deleted}, function(err, messages) {
            if(err) {
                req.send(err);
            }
            res.json(messages);
        })
    } else if(readed){
        Message.find({to: req.user.email, readed: readed}, function(err, messages) {
            if(err) {
                req.send(err);
            }
            res.json(messages);
        });
    } else if(from){
        Message.find({to: req.user.email, from: from}, function(err, messages) {
            if(err) {
                req.send(err);
            }
            res.json(messages);
        });
    }
};

1 个答案:

答案 0 :(得分:1)

只是有条件地构建您的查找查询对象,我认为这是通用的,只需要根据需要添加到allowedParams

exports.getMessages = function (req, res) {

    var allowedParams = [
        'deleted',
        'readed',
        'from'
    ];

    var query = {
        to: req.user.email
    };

    for(param in req.query) {
        if(allowedParams.indexOf(param) !== -1) {
            query[param] = req.query[param];
        }
    }

    Message.find(query, function (err, messages) {
        if(err) {
            res.send(err);
        }
        res.json(messages);
    });
}