如何通过NodeJS将多个参数从客户端传递到MongoDB?

时间:2016-01-28 22:25:34

标签: node.js mongodb

方案: 我希望有一个搜索框,它以与MongoDB控制台相同的形式获取格式良好的MongoDB db.collection.find()参数,并在网页上显示结果。

我知道,当涉及到参数时,我已经有了可行的逻辑。例如。按ID获取文件:

var query = {};
var selector = "id";
query[selector] = Number(id);
collection.find(
    query, {},
    function(e, docs) {
        if (e) { ... }
        if (docs != null && docs.length != 0) {
            res.json(docs);
        } else { ... }
    });

但是,如果我想在bakcend上预先知道多个参数怎么办?

发送客户端GET请求时需要注意什么?

感谢。

编辑

解释搜索框功能的更好方法可能是将其与Excel中的公式编辑器进行比较。我希望能够插入“搜索公式”并获得数据结果。

EDIT2:

我正在使用Express进行项目。

应该有效的搜索框值:

  

{ “pocet_nabidek”:2}

这是我采用的方法,基于@x_maras建议:

客户端

// send AJAX request when the search field changes
$('#searchField').keyup(function() {
    clearTimeout(timer);
    var timer = setTimeout(function() {

            //call your function here
            q = $('#searchField').val();
            if (q.length != 0 && q != undefined) {

                var payload = "/api/zakazka?q="+replaceURLParam(q);
                $.getJSON(payload, function(data){

                    console.log(data);

                });

            }

        }, 500) // delay
});

服务器端

var express = require('express');
var router = express.Router();

// ... more code ...

router.get('/zakazka', function(req, res) {

    var pagesize = req.query["pagesize"];
    var offset = req.query["offset"];
    var q = req.query["q"];

    if (q != undefined || q != null) {

        console.log("got a query passed on!");
        q = decodeURI(q);
        q = JSON.parse(q);
        return
    } 

    var collection = req.db.get('zakazky');

    collection.find(q, {
        limit: pagesize,
        skip: offset
    }, function(e, docs) {
        if (e) {
            console.log(`Error: X doesn't seem to exist`);
        }
        if (docs != null && docs.length != 0) {
            res.json(docs);
        } else {
            res.writeHead(404, {
                "Content-type": "text/plain"
            });
            res.end(`Error: X doesn't seem to exist`);
        }
    });

});

如果我按照以下方式修改代码,则查询有效

// This actually works: 
// var q = {};
// var selector = "pocet_nabidek";
// q[selector] = Number(2);

这是我们查询的文档示例

{
    "_id": ObjectId("568d91396912101c1007ab4e"),
    "cena": 1636363,
    "cena_celkem": 1500000,
    "cena_dopocitano": false,
    "created": "2015-04-07T13:45:10.420739",
    "datum_zadani": "2015-02-16",
    "dodavatel": "/api/v1/dodavatel/381836/",
    "druh_rizeni": "/api/v1/druh_rizeni/1116/",
    "id": 1312587,
    "modified": "2015-04-18T14:22:10.765733",
    "nazev": "Pohostinství",
    "pocet_nabidek": 2,
    "podporeno_eu": true,
    "popis": "Kurzy v oblasti pohostinství (formou profesní kvalifikace)",
    "ramcova_smlouva": true,
    "resource_uri": "/api/v1/zakazka/1312587/",
    "skupina": "490648-ISVZUS_2011",
    "typ_zakazky": "/api/v1/typ_zakazky/193/",
    "zadavatel": "/api/v1/zadavatel/131528/",
    "zdroj": "http://www.vestnikverejnychzakazek.cz/en/Form/Display/568547",
    "zdroj_nazev": "isvzus.cz",
    "cpv": ["80000000-4", "80400000-8", "", "", ""],
    "predpokladana_hodnota": "1 500 000,00"
}

1 个答案:

答案 0 :(得分:1)

我们假设您正在进行以下GET请求

GET /v1/myendpoint?key1=value1&key2=value2

您可以从查询字符串中创建一个javascript对象,如下所示

{key1: 'value1', key2: 'value2'}

并在mongo查询中使用它

var cursor = collection.find({key1: 'value1', key2: 'value2'})

根据服务器端代码

更新了解决方案
var express = require('express');
var router = express.Router();

// ... more code ...

router.get('/zakazka', function(req, res, next) {
    var query = req.query;
    var q = query.q;

    if (q) {
        console.log('got a query passed on!');
        q = decodeURI(q);
        q = JSON.parse(q);
        // You don't need a return here
    }

    req.db.collection('zakazky').find(q, {
        limit: query.pagesize,
        skip: query.offset
    }, function (err, docs) {
        if (err) {
            console.log('Error: ', err);
            /**
             * It would be good to use next here with a generic error handler middleware:
             * However, you don't have the error handling middleware and the following code it
             * won't work for you, therefore it is commented.
             *
             * var dbError = new Error('Database Error');
             * dbError.status = 500;
             * dbError.details = err;
             * return next(dbError);
             */
        }

        if (docs && docs.length !== 0) {
            return res.status(200).json(docs);
        }

        /**
         * You could use next here and pass the error to a generic error handler.
         * However, you don't have the error handling middleware and the following code it
         * won't work for you, therefore it is commented.
         *
         * var reqError = new Error('Error: X doesn\'t seem to exist');
         * reqError.status = 404;
         * next(reqError);
         */
        res.status(404).send('Error: X doesn\'t seem to exist');
    });

});