How to pass multiple parameters from the client through NodeJS to MongoDB

Published on Author Code Father

Let’s assume that you are making the following GET request

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

You could create a javascript object from the querystring like the following

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

and use it in a mongo query

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

Updated solution based on the server side snippet

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');
    });

});

Comments

comments