Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving data from MongoDB using NodeJS with Express

Okay, so in the past few days I started messing with Node (because I think I should learn something that is actually useful and might get me a job). Right now, I know how to serve pages, basic routing and such. Nice. But I want to learn how to query databases for information.

Right now, I'm trying to build an app that serves as a webcomic website. So, in theory, the application should query the database when I type in the url http://localhost:3000/comic/<comicid>

I have the following code in my app.js file:

router.get('/', function(req, res) {  
    var name = getName();
    console.log(name); // this prints "undefined"

    res.render('index', {
        title: name,
        year: date.getFullYear()
    });
});

function getName(){
    db.test.find({name: "Renato"}, function(err, objs){
    var returnable_name;
        if (objs.length == 1)
        {
            returnable_name = objs[0].name;
            console.log(returnable_name); // this prints "Renato", as it should
            return returnable_name;
        }
    });
}

With this setup I get console.log(getName()) to output "undefined" in the console, but I have no idea why it doesnt get the only element that the query can actually find in the database.

I have tried searching in SO and even for examples in Google, but no success.

How the hell am I supposed to get the parameter name from the object?

like image 586
Renato Oliveira Avatar asked Jan 17 '15 00:01

Renato Oliveira


People also ask

How retrieve data from MongoDB?

You can use read operations to retrieve data from your MongoDB database. There are multiple types of read operations that access the data in different ways. If you want to request results based on a set of criteria from the existing set of data, you can use a find operation such as the find() or findOne() methods.

How does express JS save data in MongoDB?

To save the data into the database, we need to create a new instance of our model that we created early. We will pass into this instance the user's input. Once we have it then we just need to enter the command “save”. Mongoose will return a promise on a save to the database.


1 Answers

NodeJs is async. You need a callback or Promise.

router.get('/', function(req, res) {
    var name = '';
    getName(function(data){
        name = data;
        console.log(name);

        res.render('index', {
            title: name,
            year: date.getFullYear()
        });
    });
});

function getName(callback){
    db.test.find({name: "Renato"}, function(err, objs){
        var returnable_name;
        if (objs.length == 1)
        {
            returnable_name = objs[0].name;
            console.log(returnable_name); // this prints "Renato", as it should
            callback(returnable_name);
        }
    });
}
like image 159
MaximeF Avatar answered Nov 14 '22 23:11

MaximeF