retrieving data from mongodb in jade template - node.js

I'm new to node and mongodb and am trying to render a database query in a template, but I get the error that the property is undefined:
Cannot read property 'firstname' of undefined
Here's my index.js file:
var dburl = 'localhost/olpdb';
var collections = ['users'];
var db = require('mongojs').connect(dburl, collections);
var currentUsers = db.users.find();
exports.index = function(req, res){
res.render('index', currentUsers);
};
In the index.jade template, I've got:
#{currentUsers.firstname}
I've queried the database separately and know that there is a record:
> db.users.find()
{ "firstname" : "andy", "lastname" : "johnson", "email" : "andy#johnson.com", "_id" : ObjectId("51adf8a8c58996cf0c000001") }
Can anyone help me with what I'm doing wrong? I'm trying to pass the object to the template so that I can extract the data.

In your code, currentUsers is probably an API object (a Query or similar). In order to use the query's result, you need to use a callback:
exports.index = function(req, res){
db.users.find(function(err, currentUsers) {
res.render('index', {
currentUsers: currentUsers
});
});
};
Now you can use the currentUsers array from your Jade template:
#{currentUsers[0].firstName}

Related

Connecting Node.js to MongoDB using monk

I am trying to store the data written in jade to be stored in MongoDB using monk, but it is neither storing the data nor prompting any error
connecting to MongoDB code: (p1 is the name of the database)
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/p1');
index.js code to store in DB:
/* GET New User page. */
router.get('/addnew', function(req, res) {
res.render('addnew', { title: 'Add New Theatre' });
});
/* POST to Add User Service */
router.post('/addnew', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var theatrename = req.body.TheatreName;
var screen = req.body.Screen;
var latitude = req.body.Latitude;
var longitude = req.body.Longitude;
var city = req.body.City;
// Set our collection (Theatre is the name of the collection)
var collection = db.get('Theatre');
// Submit to the DB
collection.insert({
"TheatreName" : theatrename,
"Screen" : screen,
"Latitude" : latitude,
"Longitude" : longitude,
"City" : city,
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("Not adding into db.");
}
else {
// And forward to success page
res.send("Theatrelist");
}
});
});
module.exports = router;
This is my jade code:
extends layout
block content
h1= title
form#formAddUser(name="adduser",method="post",action="/adduser")
p Thearte Name:
input#inputName(type="text", name="ThearteName")
br
p Screen :
input#inputScreen(type="text", name="Screen")
br
p Latitude:
input#inputUserLat(type="text", name="Latitude")
br
p Longitude:
input#inputlong(type="text", name="Longitude")
br
p City:
input#inputCity(type="text", name="City")
br
br
button#btnSubmit(type="submit") submit
If I were you I will try to do this:
show in console that vars from "req.body.VAR" are send correctly.
For example
router.post('/addnew', function(req, res) {
console.log(req.body.Screen);
Then, I will try to add some data to the BD for example:
collection.insert({
"TheatreName" : "Fakename",
"Screen" : "Fakescreen",
"Latitude" : "0",
"Longitude" : "0",
"City" : "Fakecity",
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("Not adding into db.");
}
else {
// And forward to success page
res.send("Theatrelist");
}
});
If you can see the result in your BD, all is OK (else, is in connection or something similar).
I hope my answer will help you!

Express: How to send multiple records to the view and access it

I am developing an application in Express with Mongo. What I have to do is to read multiple records from db and send it to view. There I have to render those in table. This is, i have done so far:
my router:
router.route('/dashboard').get(function (req, res, next) {
res.format({
html: function () {
mongoose.model('Register').find({'userid': req.session.email}, function (err, users) {
var userMap={};
users.forEach(function(user){
userMap[user._id]=user;
});
res.json(userMap);
});
}
});
});
Here is what I get in the view:
I want to render it in the view like this:
table
tbody
tr
td #{user.pid}
td #{user.sid}
td #{user.rfname}
td #{user.des}
I refered to this but it doesn't tell how to access each record in the view? any help?
instead try like this so you will have all the data into the user object res.json({user:userMap}); So that you can access it using the user object.So use the object to access elements like user[0].pid
router.route('/dashboard').get(function (req, res, next) {
mongoose.model('Register').find({'userid': req.session.email},function (err, users) {
var userMap={};
users.forEach(function(user){
userMap[user._id]=user;
});
res.render('myviewname',{user:userMap});
});
});
Replace res.send() with res.json() so you get json object into view.
If you are using express generator or similar dir structure, you can pass the data from controller to view as an object and use a for-loop to iterate through each record and print in views. Check below example to get better idea :
routes/users.js (controller file)
/* GET users listing. */
router.get('/', async (req, res) => {
const userData = await UserModel.find({}); // I'm using mongoose schema and model
res.render('user', {userData: userData});
});
views/user.jade (view file)
table(border='1')
tbody
tr
th First Name
th Last Name
th Email
th Phone
for user in userData
tr
td #{user.firstName}
td #{user.lastName}
td #{user.email}
td #{user.phone}
This is my data :
[{ "_id" : ObjectId("5f9665e318ec5a064a7ae4ad"), "firstName" : "Anil", "lastName" : "Raj", "email" : "anil#gmail.com", "phone" : "7861171771", "password" : "123456" }, { "_id" : ObjectId("5f966eb518ec5a064a7ae4ae"), "firstName" : "Arun", "lastName" : "Raj", "email" : "arun#gmail.com", "phone" : "7861171773", "password" : "123456" }]

How to loop over mongodb array with express and monk to create a page for each element?

I am building a web app with express, nodejs and monk. I am trying to create a page for each element of an array in my mongodb database.
That data is already in the collection called collections with the key coll_list like so:
{ "_id" : ObjectId("53dbaefd3d85d57492506f1f"), "coll_list" : [ "data_pagename1",
"data_pagename2", "data_pagename3" ] }
I thought it might be possible to loop over all the elements in coll_list with something like:
router.get('/index', function(req, res) {
var db = req.db;
var collection = db.get('collections');
collection.find( "coll_list" , function(e,docs) {
for (elems in docs) {
res.render(elems, {
elems : docs
});
}
});
});
Any suggestions or help/pointers on how to do this would be greatly appreciated.
Use req.params
router.get('/coll/:id',
function(req,res){
//access the id by req.params.id
//req.params.id will essentially be the _id of the document
//use it to obtain data from mongoDB and render the page using that data
//From the front end you make the call to /coll/<ObjectId> like
// /coll/53dbaefd3d85d57492506f1f and you get that id in req.params.id and use it to
//render data specific to that _id.
});
Thus, using a single route you would be able to create a page for every item in coll_list

Node.js with mongo - Rendering "object" instead the data inside the template?

Check my code...
var swig = require('swig');
var config = require('../config.json');
var mongojs = require('mongojs');
var ObjectId = mongojs.ObjectId;
var db = require('mongojs').connect(config.mongoDB, config.mongoDBcollections);
var roles;
db.lists.find({type:'roles'}).toArray(function(err, item) {
roles = item[0].data;
console.log(roles);
});
var sharetpl = swig.compileFile(__dirname +'/../html/register.html');
exports.index = function(req, res){
var output = sharetpl({
'title': 'Roles Itself',
'roles' : [roles]
});
res.send(output);
};
this is the console.log output...
[ { name: 'Web Developer', code: 'wdv' },
{ name: 'Web Designer', code: 'wds' },
{ name: 'System Archtect', code: 'sar' } ]
It's all okay, so far...but the html...
server side: <|-- {{roles}} -->
client html :
<|-- [object Object],[object Object],[object Object] -->
So, basically I'm stucked on it...It's rendering "[object Object]" on the client side instead the data itself :( pretty frustrated. Any clue ? ty !
roles is an array of Objects, so you need to refer to specific fields of each individual object in array.
if you are using Mustache the syntax will be as follows:
{{#roles}}
{{name}}, {{code}}
{{/roles}}

How to write a common function to fetch a collection of records in Node.js from Mongodb

I am using
app.get('/', function(req, res){
var listData = function(err, collection) {
collection.find().toArray(function(err, results) {
res.render('index.html', { layout : false , 'title' : 'Monode-crud', 'results' : results });
});
}
var Client = new Db('monode-crud', new Server('127.0.0.1', 27017, {}));
Client.open(function(err, pClient) {
Client.collection('users', listData);
//Client.close();
});
})
This method to get records from mongoDB and showing in a html.
I am using Express, hbs as view engine.
I need a common method where I can pass collection name or mongo query,
it should return the collection as result.
In the main page i can process the collection.
Just like splitting data logic in separate classes in C#.
How to achieve this?

Resources