essxiv essxiv - 3 months ago 19
Node.js Question

Sailsjs not displaying model data associations in view

Using Sails.js v0.12.4 and Node.js v6.4.0.

I'm trying to display a One to Many association using MVC into a specific view.

User.js

module.exports = {
attributes: {
tickets: {
collection: 'ticket',
via: 'owner'
}
}
}


Ticket.js

module.exports = {
attributes: {
owner: {
model: 'user'
}
}
}


UserController.js

show: function(req, res, next) {
User.findOne(req.param('id')).exec(function(err, user) {
if (err) next(err);
if (!user) return next();
res.view({
user: user,
userTickets: user.tickets
});
});
},


/edit/user/show.ejs

<% _.each(userTickets, function (ticket) { %>
<tr data-id="<%= ticket.id %>" data-model="ticket">
<td> <%= ticket.id %> </td>
<td> <%= ticket.ticketName %> </td>

<td><a href="/ticket/show/<%= ticket.id %>">Show</a></td>
<td><a href="/ticket/edit/<%= ticket.id %>">Edit</a></td>
<td><a href="/ticket/destroy/<%= ticket.id %>">Delete</a></td>
</tr>
<% }) %>


I'm even finding the association in my MongoDB Database:

A Ticket Object Belonging to: "57c1207dea46efef0c0cd27d"

{
"_id" : ObjectId("57c27f6de4c7fd2d036a96b5"),
"owner" : ObjectId("57c1207dea46efef0c0cd27d"),
"ticketName" : "asdfasdfasdfasdfasdf",
"createdAt" : ISODate("2016-08-28T06:06:37.085Z"),
"updatedAt" : ISODate("2016-08-28T06:06:37.085Z")
}


The User Object

{
"_id" : ObjectId("57c1207dea46efef0c0cd27d"),
"firstName" : "Dan",
"lastName" : "Michaels",
"email" : "DM@nike.com",
"createdAt" : ISODate("2016-08-27T05:09:17.598Z"),
"updatedAt" : ISODate("2016-08-27T05:09:17.598Z")
}


It's not displaying anything in my /show.ejs page..

Answer

change

User.findOne(req.param('id')).exec(function(err, user) {

to

User.findOne(req.param('id')).populate('tickets').exec(function(err, user) {

http://sailsjs.org/documentation/reference/waterline-orm/queries/populate

That should do it.

Comments