Skip to content Skip to sidebar Skip to footer

Display The Data Onto Webpage Retrieved From Mongodb Using Node.js

Heres my problem. Might be a bit trivial. I am using node.js to write a form which has radio buttons, drop down boxes. I have been able to save data and also retrieve it successful

Solution 1:

You can do this pretty easily with express and mongoose. First you would connect to mongoDB using mongoose, and then set up some of the variables used to interact with mongoDB from mongoose (i.e. mongoose.scheme & mongoose.model), and finally you simply send your mongoDB data to a web page through express's res.render function:

mongoose.connect('mongodb://localhost/test', function(err){
    if(!err){
        console.log('connected to mongoDB');
    } else{
        throw err;
    }
});

varSchema = mongoose.Schema,
    ObjectID = Schema.ObjectID;

varPerson = newSchema({
    name : String
});

varPerson = mongoose.model('Person', Person);   

app.get('/', function(req, res){
    Person.find({}, function(err, docs){
        res.render('index', { docs: docs});
    });
});

After sending the data, you can simply reference the 'docs' variable in your web page. Express automatically uses the Jade framework. In Jade you could do something like list all the names of the people in your database:

- if(docs.length)
    each person in docs
      p #{person.name}
- else
    p No one isin your database!

Post a Comment for "Display The Data Onto Webpage Retrieved From Mongodb Using Node.js"