【发布时间】:2014-12-19 13:43:36
【问题描述】:
我知道 Sails.js/Waterline 中还没有内置的方式来填充深层嵌套关联,所以我尝试使用 bluebird 承诺来实现这一点,但我遇到了问题。
我成功检索了用户,以及与之关联的所有帖子(填充了图像集合)(console.log 显示所有内容都已正确填写)。但是,当我覆盖用户的属性“post”并尝试分配之前检索到的完全填充的帖子时,它没有正确填充 Post.js 的 images 属性。就像是ORM阻止了Post.js的图像集合被手动分配。
我做错了什么?填充深层嵌套的一对多关联的最佳方法是什么?
下面我已经粘贴了我正在执行的所有代码......
// 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"
}
},
}
问候,
萨维奥·卢塞纳
【问题讨论】:
标签: javascript sails.js waterline