JohnSnow
JohnSnow

Reputation: 7121

req.params does not work in mongo query

this may be a bit difficult to explain, so I will be as clear as possible.

const express = require("express");
const router = express.Router();
const mongo = require("mongodb");
const linkId = require("./newRoute");

const DBusername = process.env.username;
const DBpassword = process.env.password;

const numbersOnly = new RegExp('^[0-9]+$');

var linkArr = [];

router.get("/:url", function (req, res) {
    if (numbersOnly.test(req.params.url)) {
        mongo.MongoClient.connect(mongoUrl, function (err, db) {
            if (err) throw err;
            console.log("connection established")
            var cursor = db.collection("urls").find({ "id":linkId.id});
            cursor.forEach(function (doc, err) {
                if (err) throw err;
                linkArr[0] = doc.href;
            }, function () {
                db.close();
                res.redirect(linkArr[0])  
            })
        })
    } else {
        res.json({ "error": "This url is not on the database." })
    }
});

I am trying to query the database with an id number which will respond with a respective URL, and redirect to that URL. The database is filled with URLS and their respective id numbers. As you can see the code below will query the database with this line:

var cursor = db.collection("urls").find({ "id":linkId.id});

linkId.id is the id of the recently inserted URL imported from another file. And everything works perfectly. However if I use this line instead:

var cursor = db.collection("urls").find({ "id":req.params.url});

The cursor forEach never gets executed and I have access to the req.params.url so I don't get any errors. I don't want the id to be imported from a different file, I want the id (which is used to query the database) to be extracted from req.params.url. How come this isn't working, it's boggling my mind.

Upvotes: 0

Views: 1555

Answers (1)

Noah Wallace
Noah Wallace

Reputation: 118

Very possibly because req.params.url is being passed as a string instead of a number. Mongo is very sensitive to data types and all items passed in req.params are considered strings with no casting. No values will be returned if a mongo document value is a number when querying for a string.

A plain text parser can help you with that like mongo-qp

Upvotes: 1

Related Questions