我明白Sails.js / Waterline中没有嵌入深入的嵌套关联的内置方式,所以我试图用蓝鸟的承诺来完成这个,但是我遇到了一个问题.
我成功检索到用户,以及与它相关联的所有帖子(填充图像集合)(console.log显示我的所有内容都正确填写).但是,当我覆盖用户的属性“post”,并尝试分配之前检索的完全填充的帖子,它不能正确填充Post.js的图像属性.就像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"
}
},}
问候,
萨维奥·卢塞纳
解决方法
这可能是一个古老的问题,但是更好的是有一个答案,所以sails.js的用户可以从中受益.
这里的问题是当sails返回一个记录(数组内部)时,与记录相对应的记录的键实际上是getter / setter,似乎setter不允许你想要的.您可以使用Object.getownPropertyDescriptor(user,’posts’)进行确认.
所以为了能够根据需要重写该属性,您需要执行的操作就是在其上调用.toObject(或者通过_.clone或手动循环来克隆其属性,但是你会得到很多垃圾,所以坚持.toObject),在任何情况下,您将获得一个新的对象与您需要的属性,并没有限制如何修改它现在.
所以你的代码将如下所示:
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){
user = user.toObject() // <- HERE IS THE CHANGE!
user.posts = posts; // It will work Now
res.json(user);
}).catch(function (err){
if (err) return res.serverError(err);
});
}