gpt4 book ai didi

javascript - Sails.js/Waterline 填充深层嵌套关联

转载 作者:可可西里 更新时间:2023-11-01 02:22:48 25 4
gpt4 key购买 nike

我知道 Sails.js/Waterline 中还没有填充深层嵌套关联的内置方法,所以我尝试使用 bluebird promises 来完成它,但我遇到了问题。

我成功地检索了用户,以及与之关联的所有帖子(填充有图像集合)(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 返回一个记录(在数组内)时,对应于关联的记录的键实际上是 getters/setters,似乎 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];
})
.spread(function (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);
});
}

关于javascript - Sails.js/Waterline 填充深层嵌套关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26535727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com