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}.
Related
I am trying to get the object from the frontend but the problem i am facing is that the fronend is sending that object in qoutes
Preview URL: false
[Object: null prototype] {
name: 'Arun Teltia',
email: 'acfsdzvff#gmail.com',
message: 'test',
'g-recaptcha-response': '',
contact: 'contact'
}
here is the response i am getting i want to extract g-recaptcha-response in my backend how can i do that?
I tried to explain as much as i can and also i tried to search on google but i was not able to find something ,Thank you for the help in advance :D
You can use the bracket notation to access a property of an object:
obj['g-recaptcha-response']
See Property accessors
I've passed an object to my jade template from express:
connection.invokeQuery(sqlStatement, function(rows){
res.render('index', { title: 'App', companies: rows});
});
here's my template
extends layout
block content
h1= title
div
each company in companies
p #{company.City}
that works, I can render a city list. But I'm not sure how to get at the root property or sub properties and objects within an object with jade.
For example lets say the json for company was this:
[{
companyName: 'Apple',
City: 'Milwaukee',
State: 'WI ',
StateName: 'Wisconsin',
Country: 'United States',
Region: 'North America',
PostalCode: '53201-0371'},
{
Website: 'www.apple.com',
....
},
... and so on
}]
I tried company.companyName and it doesn't work.
Also how would I reference the property "Website"? It's in another object below in this array.
From what I'm seeing here, you have multiple objects inside an array. You wouldn't be able to access "Website" as it is in another object. The each statement is iterating over the array containing your objects. You could access it in the second iteration of your each statement, but no other properties of the first object. If you wanted access to that value, it must be a part of the same object.
I'm working with an Ember app that ties into a Rails backend through a Sails.js API, and ran into an issue I can't find any similar examples for.
My Messages model has a sender_id column, which corresponds with the id column in my Users model. There is also a Profile model (belongs to User through user_id) that contains the username column, which is what I'd like to be able to access through the Messages model as 'senderName' (i.e., message.senderName). My models and routes are all hooked up, so I have access to all the data I need and everything displays correctly in the browser aside from my senderName function.
The plan was to look up the Profile object through its user_id (using sender_id) inside of Messages, then pull the username field from there. I've been able to receive Promises back from my Profile query, but from there I'm not sure how/if I can access the actual username field. Is there a way to do this, or am I trying to fit a square peg into a round hole?
I also tried accessing username by looking up the User object first (this.store.find('user'), etc.) and using my Rails associations for user.profile.username, but that didn't work either.
Models:
App.Message = DS.Model.extend({
sender_id : DS.attr('number'),
content : DS.attr('string'),
senderName: function() {
var id = this.get('sender_id');
var profile = this.store.find('profile', {user_id: id}).then(function() {
console.log(profile);
// What next? profile.username doesn't work
})
}.property('sender_id')
});
App.Profile = DS.Model.extend({
user: DS.belongsTo('user', { async: true }),
username : DS.attr('string'),
user_id : DS.attr('number')
});
App.User = DS.Model.extend({
profile: DS.belongsTo('profile', { async: true }),
email: DS.attr('string'),
name: DS.attr('string')
});
Template:
<script type="text/x-handlebars" data-template-name="messages/index">
<div class="small-12 column">
{{#each message in model}}
<p>From: {{message.senderName}}</p>
<p>Content: {{message.content}}</p>
{{/each}}
</div>
</script>
Here's an example of the promises I'm receiving back in the browser console:
Promise {_id: 93, _label: undefined, _state: undefined, _result: undefined, _subscribers: Array[0]…}
Thanks for your help!
If I'm getting the question correct, you are having trouble accessing the fields in the model? If so, try:
profile.get('username')
You're really overcomplicating this :-)
Message also belongs to sender, why did you define sender_id as a number?
If you delete senderName and change the sender_id property to:
sender: DS.belongsTo('user', { async: true }),
You can use message.get('sender.profile.username'). I think your main issue here is that you're trying to do an async operation in the computed property, which is a no-no. You can alias the senderName if you like, via senderName: Ember.computed.alias('sender.profile.username') if you end up using it a lot.
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?
I have some information on my mongoose models which is transient. For performance reasons I dont wish to store it against the model.. But I do want to be able to provide this information to clients that connect to my server and ask for it.
Here's a simple example:
var mongoose = require('mongoose'),
db = require('./dbconn').dbconn;
var PersonSchema = new mongoose.Schema({
name : String,
age : Number,
});
var Person = db.model('Person', PersonSchema);
var fred = new Person({ name: 'fred', age: 100 });
The Person schema has two attributes that I want to store (name, and age).. This works.. and we see in the console:
console.log(fred);
{ name: 'fred', age: 100, _id: 509edc9d8aafee8672000001 }
I do however have one attribute ("status") that rapidly changes and I dont want to store this in the database.. but I do want to track it dynamically and provide it to clients so I add it onto the instance as a key/val pair.
fred.status = "alive";
If we look at fred in the console again after adding the "alive" key/val pair we again see fred, but his status isnt shown:
{ name: 'fred', age: 100, _id: 509edc9d8aafee8672000001 }
Yet the key/val pair is definitely there.. we see that:
console.log(fred.status);
renders:
alive
The same is true of the JSON representation of the object that I'm sending to clients.. the "status" isnt included..
I dont understand why.. can anyone help?
Or, alternatively, is there a better approach for adding attributes to mongoose schemas that aren't persisted to the database?
Adding the following to your schema should do what you want:
PersonSchema.virtual('status').get(function() {
return this._status;
});
PersonSchema.virtual('status').set(function(status) {
return this._status = status;
});
PersonSchema.set('toObject', {
getters: true
});
This adds the virtual attribute status - it will not be persisted because it's a virtual. The last part is needed to make your console log output correctly. From the docs:
To have all virtuals show up in your console.log output, set the
toObject option to { getters: true }
Also note that you need to use an internal property name other than status (here I used _status). If you use the same name, you will enter an infinite recursive loop when executing a get.
Simply call .toObject() on the data object.
For you code will be like:
fred.toObject()
This has been very helpful. I had to struggle with this myself.
In my case, I was getting a document from mongoose. When I added a new key, the key was not visible to the object if I console.log it. When I searched for the key (console.log(data.status), I could see it in the log but not visible if I logged the entire object.
After reading this response thread, it worked.
For example, I got an object like this one from my MongoDB call:
`Model.find({}).then(result=> {
//console.log(result);// [{ name:'John Doe', email:'john#john.com'}];
//To add another key to the result, I had to change that result like this:
var d = result[0];
var newData = d.toJSON();
newData["status"] = "alive";
console.log(newData);// { name:'John Doe', email:'john#john.com', status:'alive'};
}).catch(err=>console.log(err))`
Hope this helps someone else.
HappyCoding