Sails.js填充嵌套關聯我自己有一個關于Sails.js版本0.10-rc5中的關聯的問題。我一直在構建一個應用程序,其中多個模型相互關聯,我到達了一個我需要以某種方式獲得嵌套關聯的點。有三個部分:首先是博客文章,這是由用戶編寫的。在博客文章中,我想顯示關聯用戶的信息,如用戶名?,F在,這里一切正常。直到下一步:我正在嘗試顯示與帖子相關的評論。注釋是一個單獨的模型,稱為Comment。每個人還有一個與之相關的作者(用戶)。我可以輕松地顯示評論列表,但是當我想顯示與評論相關的用戶信息時,我無法弄清楚如何使用用戶的信息填充評論。在我的控制器中,我試圖做這樣的事情:Post
.findOne(req.param('id'))
.populate('user')
.populate('comments') // I want to populate this comment with .populate('user') or something
.exec(function(err, post) {
// Handle errors & render view etc.
});在我的Post''show'動作中,我試圖檢索這樣的信息(簡化):<ul>
<%- _.each(post.comments, function(comment) { %>
<li>
<%= comment.user.name %>
<%= comment.description %>
</li>
<% }); %></ul>但是,comment.user.name將是未定義的。如果我嘗試只訪問'user'屬性,例如comment.user,它會顯示它的ID。這告訴我,當我將評論與其他模型關聯時,它不會自動將用戶的信息填充到評論中。任何理想的人都能妥善解決這個問題:)?提前致謝!PS為了澄清,這就是我基本上在不同模型中建立關聯的方式:// User.jsposts: {
collection: 'post'}, hours: {
collection: 'hour'},comments: {
collection: 'comment'}// Post.jsuser: {
model: 'user'},comments: {
collection: 'comment',
via: 'post'}// Comment.jsuser: {
model: 'user'},post: {
model: 'post'}
3 回答

慕尼黑的夜晚無繁華
TA貢獻1864條經驗 獲得超6個贊
或者您可以使用內置的Blue Bird Promise功能來制作它。(致力于[email protected])
請參閱以下代碼:
var _ = require('lodash');...Post .findOne(req.param('id')) .populate('user') .populate('comments') .then(function(post) { var commentUsers = User.find({ id: _.pluck(post.comments, 'user') //_.pluck: Retrieves the value of a 'user' property from all elements in the post.comments collection. }) .then(function(commentUsers) { return commentUsers; }); return [post, commentUsers]; }) .spread(function(post, commentUsers) { commentUsers = _.indexBy(commentUsers, 'id'); //_.indexBy: Creates an object composed of keys generated from the results of running each element of the collection through the given callback. The corresponding value of each key is the last element responsible for generating the key post.comments = _.map(post.comments, function(comment) { comment.user = commentUsers[comment.user]; return comment; }); res.json(post); }) .catch(function(err) { return res.serverError(err); });
一些解釋:
我正在使用Lo-Dash來處理數組。有關詳細信息,請參閱官方文檔
注意第一個“then”函數內的返回值,數組中的那些對象“[post,commentUsers]”也是“promise”對象。這意味著它們在首次執行時不包含值數據,直到它們獲得值。因此,“傳播”功能將等待動作值來繼續做剩下的事情。
- 3 回答
- 0 關注
- 710 瀏覽
添加回答
舉報
0/150
提交
取消