InquisitiveGirl
InquisitiveGirl

Reputation: 687

Express JS routing based on the user names

I am working on a express js project.I have got all my basic routing set up working perfectly. Usually when I want to search a record based on id I do this:

    router.route('/sensors_home/:sensor_id')
.get(function (req, res) {
        Sensor.findById(req.params.sensor_id,function(err, sensorInfo) {
            if (err)
                res.send(err);
            res.send(sensorInfo);
        });
    });

This allows me to retrieve the data when I do http://localhost:4000/sesnors_home/45000cbsfdhjbnabfbajhdb

(45000cbsfdhjbnabfbajhdb = Object id from the MongoDB )

Now my goal is to have several users to my application. I have my mongoose schema set up and the mongoDB looks like this :

data

Here is the issue: I wanna retrieve data corresponding to John Peterson based on his _id that is "John".Instead of doing this http://localhost:4000/sesnors_home/45000cbsfdhjbnabfbajhdb I wanna do something like this http://localhost:4000/sesnors_home/John and retrieve all the data specific to John. I tried various methods but still stuck with this issue. I tried using req.params._id and also some Mongodb queries on the User Collection but still no luck. Please suggest some ideas.

Thanks!

UPDATE:

I tried using the following code :

router.route('/sensors_home/:id')
.get(function (req, res) {
res.send(_id.toString());
    User.findOne({_id: req.params._id} ,function(err, sensorInfo) {
        if (err)
            res.send(err);
        res.send(sensorInfo);
    });
});

This gives me the following error : ReferenceError: _id is not defined

Upvotes: 0

Views: 84

Answers (1)

Thomas Wolfe
Thomas Wolfe

Reputation: 638

Have you tried the following?

router.route('/sensors_home/:_id')
.get(function (req, res) {
        Sensor.findOne({_id: req.params._id},function(err, sensorInfo) {
            if (err)
                res.send(err);
            res.send(sensorInfo);
        });
    });

Upvotes: 1

Related Questions