Reputation: 594
How to find mongo data(db.collection_name.find())
through express route and print the data into jade template.
Here is my express route( I am using express2.5.8)
app.get('/showData',function(req,res){
db.collection('comments',function(err, data){
if(err){
throw err;
}
else{
data.find();
res.render('help', {data: data});
}
});
});
It through an error that db.collection
is not a function
Upvotes: 0
Views: 1554
Reputation: 594
I find the answer myself below is the code:
Controller :
company.find({}, function(err, companies) {
if (err){
callback(err);
}
else{
callback(null, companies);
}
});
Route :
app.get('/companies', isLoggedIn,function(req, res) {
companyCtrl.companyList(function(err, companies){
res.render('companies',{companies:companies});
});
});
Jade Template :
each val in companies
tr
td(data-field="state" data-checkbox="true" ) ID
td(data-field="id" data-sortable="true")= val.id
td(data-field="name" data-sortable="true")= val.name
In the above example i have used .find method in controller to fetch the documents in the collection and send them back to the route with callback function and jade display the results in the frontend
Upvotes: 0
Reputation: 9034
For a quick start, you can connect to the db first, and then store db
in a variable:
var MongoClient = require('mongodb').MongoClient;
var database;
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
if (!err) {
console.log("Connected correctly to server");
database = db;
}
})
app.get('/showData',function(req,res){
database.collection('comments',function(err, data){
if(err){
throw err;
}
else {
data.find();
res.render('help', {data: data});
}
});
Later you can move all the db connectivity functionality into separate file and just require it when needed.
Upvotes: 1