I understand that there is no built-in way in Sails.js/Waterline of populating deep nested associations yet, so I am trying to use bluebird promises to accomplish that but I'm running into a problem.
I'm successfully retrieving the user, and all the posts (populated with the images collection) associated with it (console.log shows me that everything is filled properly). However, when I override the property "post" of the user and try to assign the fully populated posts retrieved before, it does not fill properly the images property of Post.js. It is like the ORM is preventing the image collection of Post.js to be manually assigned.
What am I doing wrong? What is the best way of populating deep nested one-to-many associations?
Bellow I've pasted all the code that I'm executing....
// Populate nested association
nested: function (req, res, next){
var username = req.param("id");
User
.findOneByUsername(username)
.populateAll()
.then(function (user){
var posts = Post.find({
"user": user.id
})
.populate('images')
.populate('category')
.then(function (posts){
return posts;
});
return [user, posts];
})
.spread(function (user, posts){
user.posts = posts; // This won't work.... It assigns all the fields properly but the images collection attribute
res.json(user);
}).catch(function (err){
if (err) return res.serverError(err);
});
}
// --- User.js Model --- //
module.exports = {
attributes: {
.....,
posts: {
collection: "post",
via: "user"
},
.....
}
}
// --- Post.js Model --- //
module.exports = {
attributes: {
....,
user: {
model: "user"
},
images: {
collection: "postImage",
via: "post"
},
....
}
}
// --- PostImage.js Model --- //
module.exports = {
attributes: {
....,
post: {
model: "post"
}
},
}
Regards,
Sávio Lucena