nodejs mongodb驱动程序本机查询问题

时间:2016-02-20 19:25:25

标签: node.js mongodb

如果我把下面的表格放在Node.js mongodb中,这会变成一个有趣的错误:

locals.collection.find(filter, req.query);

返回以下错误:

MongoError: query selector must be an object

现在,如果我手动将查询工作。 我有很长一段时间遇到这个问题,我已经尝试了几种方法。

locals.collection.find({slug:'somak'}, req.query);

我正在使用以下功能:

exports.findAll = function(req, res, next) {

    var locals  = {},
        section = req.params.section,
        query   = req.query,
        filter  = {};

    if(query.filter) {

        filter = query.filter.replace(/"(\w+)"\s*:/g, '$1:');
        filter = filter.replace(/["]/g, "'");

    }

    console.log(filter);


    delete query.filter;

    async.series([

        function(callback) {
            MongoClient.connect(url, function(err, db) {
                if (err) return callback(err);
                locals.collection = db.collection(section);
                callback();
            });
        },

        function(callback) {
            locals.collection.count(filter, function (err, result){
                if (err) return callback(err);
                locals.count = result;
                callback();
            });
        },

        function(callback) {

            var cursor = locals.collection.find({slug:'somak'}, req.query);

            if(req.query.page) {
                cursor = cursor.skip(Math.abs(req.query.limit) * --req.query.page);
            }

            cursor.toArray(function(err, docs) {
                if (err) return callback(err);
                locals.docs = docs;
                callback();
            });
        }
    ],

    function(err) { //This function gets called after the three tasks have called their "task callbacks"
        if (err) return next(err);
        // Here locals will be populated with 'count' and 'docs'
        res.json({
            count: locals.count,
            data: locals.docs
        });
    });

1 个答案:

答案 0 :(得分:0)

只需使用JSON.parse:

exports.findAll = function(req, res, next) {

    var locals  = {},
        section = req.params.section,
        query   = req.query,
        filter  = {};

    if(query.filter) {
        filter = JSON.parse(query.filter);
    }

    delete query.filter;

...