Terradon
Terradon

Reputation: 858

Node.js / REST: How to get _id from url

I have followed next tutorial: http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/ After a few days I got it all working, but updating the userdatabase is for the reader themselves.

I have edited the jade template and added some javascript for a click event on an update link. I could even retrieve the userID from a listed testuser. Tested this with an alert and is ok.

javascript for click event: global.js

function showUser2Edit(event){
    event.preventDefault();

    var userID = $(this).attr('rel');
    // alert (userID);// _id from MongoDB, ok!

    // jQuery AJAX call for JSON
    $.getJSON( '/users/userdata/' + userID, function( data ) {
        // populate edit form
        alert (JSON.stringify(data));
    }
}  

in users.js (server-side node.js)

/*
 * GET userData
 */
router.get('/userdata', function(req, res) {
    var db = req.db;
    var collection = db.get('users');
        collection.find({_id: ?????? },{},function(e,docs){
        res.json(docs);
    });
});

2 problems i really have no idea how to solve them:

Ajax call will be to: users/userdata/_id (_id is a long string, automatically added as key by MongoDB). But how do I add this to this router function?

This _id must be placed in the where part of collection.find(....), but how do i extract this from the url?

Thanks in advance for any help!

The mark for duplication is not correct,that one is about a query parameter: ?color=red, how can I access the variabe color?,mines is a REST system where the id is part of the url itself.

Upvotes: 0

Views: 2538

Answers (2)

Vladyslav Mysiur
Vladyslav Mysiur

Reputation: 67

You change:

$.getJSON( '/users/userdata/' + userID, function( data ) {

To:

 $.getJSON( '/users/userdata/?id=' + userID, function( data ) {

And use in node - req.query.id.

Upvotes: 0

Vladyslav Mysiur
Vladyslav Mysiur

Reputation: 67

You need change

router.get('/userdata'...

To:

router.get('/userdata/:id'...

:id - its params. If you use body-parser in node.js that check req.body.params.

Upvotes: 4

Related Questions