Variables not showing content on Jade template - node.js

I am learning Node.js using a book. There was an example that as a learning experience I converted from what it was to a SQL version of it.
This single page is only intended to display user information. I load the user information on a middleware then pass it to the Jade template. Everything working up to this point.
When I want to render the template below, wherever I user content from the user object, it renders nothing.
h1= user.Name
h2 Bio
p= user.Bio
form(action="/users/" + encodeURIComponent(user.User), method="POST")
input(name="_method", type="hidden", value="DELETE")
input(type="submit", value="Delete")
To check if the object was without content, I added this 2 lines on the front
-console.log ( 'Inside Jade' )
-console.log ( user )
and the result in the console is:
Inside Jade
[ { Name: 'Jennifer Lopes',
User: 'jenny',
Password: 'asd',
Bio: 'Actress and singer' } ]
So this tells me that the information is there, but is not being rendered.
The code used to render the template is:
app.get ('/users/:name', loadUser, function ( req, res, next ) {
res.render ( 'users/profile', { title: 'User profile', user: req.user });
});
Can you please help me to understand what am I doing wrong? Thanks in advance.

A little hard to tell without seeing all your code, but per the output of your console it looks like user is actually an array of objects based upon the brackets, if you change your jade template to output something like user[0].Name does it give you your expected values?

Related

Return the value from a mongoose find

I'm trying to render a template when i check the link for view a profile (for example going to http://localhost:3000/user/testuser`), all ok going to the routes but the values don't being showed on the page. This is my code:
Account.find({ username: req.params.username }, function(err, userWatch){
res.render('account/profile',{
title : userWatch.username,
user : req.user,
watchUser : userWatch,
});
You are using Account.find() that returns the array of objects. You should use Account.findOne() to fetch data, if you want either one or none objects.

Display data in Jade with Mongoose

I've been trying to grab my data that's stored in mongodb and display it with a simple Jade template. I'm kinda new to this and I'm totally lost at this point.
Here's my output when I render my collection on /yfirlit
The express router for /yfirlit looks like this
apiRouter.get('/yfirlit', function(req, res){
apiUser.find(function(err, users) {
if(err) res.send(err);
res.render('yfirlit', {title: 'Yfirlit', users: users});
});
});
My simple Jade Template
html
head
title!= title
body
div #{users}
p
| API
When I run the test the whole mongodb collection is displayed on the site. What I'm looking for is to be able to display only a portion of the documents in the collections. For example: I tried to display only the name property in the Jade template but was unable to get it right.
html
head
title!= title
body
div #{users.name}
p
| API
Any help would be greatly appreciated, I'm so lost and I would love to be able to render out only the properties that I wanted instead of the whole thing like in the picture.
Cheers!
As Sgnl said, within the route you'll need to render the Jade view and include the data just like you have, but by using res.render:
apiRouter.get('/yfirlit', function(req, res){
apiUser.find(function(err, users) {
if (err) return next(err);
res.render('index', {
title: 'yfirlit',
users: users
})
});
});
...And I think you'll also need a loop to display the data from within your Jade view, because it contains multiple values:
if users
each user in users
div #{user.name}

Internationalize nodejs jade templates

I'm trying to internationalize my nodejs express app using i18n-2 module. All is working but I have a question. Is there a way to translate string from my jade templates. Imagine I have 100 strings in my website. Do I have to send 100 translations to the template through the res.render invocation?
res.render('profile', {
title: 'My cool title',
user: req.user,
hello1: req.i18n.__("hello1"),
hello2: req.i18n.__("hello2"),
hello3: req.i18n.__("hello3"),
...
helloN: req.i18n.__("helloN")
});
Is there another way to do this? Somethin like the next code:
res.render('profile', {
title: 'My cool title',
user: req.user,
i18n: req.i18n // to be used inside jade
});
i18n-2 already registers helper objects in your Express locals, which are accessible form your Jade template. These helper methods are registered automatically: "__", "__n", "getLocale", and "isPreferredLocale". Without any additional configuration, should be able to do the following in your Jade template:
a(href="/") #{ __('home') }

Why doesn't this data display?

I have the following JSON object:
{
user:
{
city: 'San Francisco',
country: 'US',
displayName: 'Bernard',
weightUnit: 'METRIC'
}
}
It comes back in the following piece of code, i.e. as a string:
var response = results[0];
I send it to the view like this:
res.render('user', {title: 'User Details', result: JSON.parse(response)});
In the view, no matter what I do, I cannot access displayName.
All I want is to this in my jade template:
h1 Hi, #{displayName}
And I keep getting user undefined, undefined of undefined, etc.
No matter how I try and access that displayName, jade/express simply cannot get to it.
Anyone have any ideas how I'd do this please?
That object that you pass in your render call becomes the context your Jade file uses. Thus, at your root, you have title and result. See where this is going?
Try h1 Hi, #{result.user.displayName}.

Access mongoose non-schema values in Jade

I have a really weird problem in Jade where I cannot access the values that aren't defined in the Schema.
I'm using strict:false on my schema and saving values to it. My data looks like this:
{
"title" : "This is a title in the schema",
"notInSchema" : "This will never show up"
}
This works:
h1= post.title
This doesn't work:
h1= post.notInSchema
If I dump all my data into the template, I can see both pieces of data:
pre= JSON.stringify(options,null,'\t') //{"title" : "This is a title in the schema", "notInSchema" : "This will never show up"}
If I add notInSchema to my schema, it shows up. How can I do this without adding it?
Instead of passing the raw Mongoose document to Jade, pass its serialized version instead:
res.render('yourtemplate', {
post : post.toJSON() // .toJSON() is also called by JSON.stringify()
});
I believe Mongoose only creates accessors on a document for fields that are in the schema. Any other fields, even though they are stored in the database, don't get one so can't be accessed directly.
The documentation seems to suggest something similar:
NOTE: Any key/val set on the instance that does not exist in your
schema is always ignored, regardless of schema option.
EDIT: since you're dealing with result sets, you need to call toJSON on each document in it. The easiest way to do so is using map (hope I get the CF syntax right):
res.render "admin",
title : "Admin Dashboard"
results : results
users : results.users.map (user) ->
user.toJSON()
messages: req.flash() || {}
Although that would still leave results 'unprocessed'. Alternatively, you could leave the mapping to the separate steps in your async.series. For instance:
Company
.find()
.exec (err,companies)->
next(null,companies.map (company) ->
company.toJSON()
)
Or use toJSON in your template on any object that you need to access those "unschema'd" properties for.
I use:
model.find({Branch:branch},function (err, docs){
if (err) res.send(err)
res.render('index',
{tree: tree,
articulos: JSON.parse(JSON.stringify(docs))
})})
});

Resources