I am creating an object from my backend sails API to send to my angular front app.
The object is created like this :
getHommeAndChevre: function (req, res) {
// console.log(req.param("id"));
Trophe.find({foot: req.param('id')}, function(err, trophes){
if(!trophes) {return res.status(400).end();}
if(trophes){
_.each(trophes, function(trophe, index){
User.find(trophe.id, function(err, user){
// console.log(user);
if (trophe.trophe == 0) {var chevre = trophe; chevre.picture = user.picture; chevre.name = user.first_name; };
if (trophe.trophe == 1) {var homme = trophe; homme.picture = user.picture; homme.name = user.first_name;};
if (index == trophes.length - 1)
return res.status(200).json({chevre: chevre, homme: homme});
});
});
}
});
}
The problem is that the objects chevre
or homme
I get back on the front-end don't include a picture
attribute & a name
attribute as I am specifying in my function here :
if (trophe.trophe == 0) {var chevre = trophe; chevre.picture = user.picture; chevre.name = user.first_name; };
if (trophe.trophe == 1) {var homme = trophe; homme.picture = user.picture; homme.name = user.first_name;};
Here is the object I get back on the front end side
As you can see there is no picture
and name
attribute in my homme object !
What am I doing wrong here ?
Use <model>.findOne()
if you're looking for a single record.
<model>.find()
always returns an Array
, so when you do User.find(trophe.id, function(err, user){}
, user.first_name will be undefined
. Instead, you would to use user[0].first_name
.
So then you might have:
homme : {
name : undefined
}
Which is then stringified (see sails docs ) by sending it into res.json()
. At that point, it is likely removed:
sails> var trophe = {name : undefined}
undefined
sails> trophe
{ name: undefined }
sails> JSON.stringify(trophe)
'{}'
sails>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.