Sails.js填充嵌套關(guān)聯(lián)我自己有一個關(guān)于Sails.js版本0.10-rc5中的關(guān)聯(lián)的問題。我一直在構(gòu)建一個應(yīng)用程序,其中多個模型相互關(guān)聯(lián),我到達了一個我需要以某種方式獲得嵌套關(guān)聯(lián)的點。有三個部分:首先是博客文章,這是由用戶編寫的。在博客文章中,我想顯示關(guān)聯(lián)用戶的信息,如用戶名?,F(xiàn)在,這里一切正常。直到下一步:我正在嘗試顯示與帖子相關(guān)的評論。注釋是一個單獨的模型,稱為Comment。每個人還有一個與之相關(guān)的作者(用戶)。我可以輕松地顯示評論列表,但是當(dāng)我想顯示與評論相關(guān)的用戶信息時,我無法弄清楚如何使用用戶的信息填充評論。在我的控制器中,我試圖做這樣的事情: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。這告訴我,當(dāng)我將評論與其他模型關(guān)聯(lián)時,它不會自動將用戶的信息填充到評論中。任何理想的人都能妥善解決這個問題:)?提前致謝!PS為了澄清,這就是我基本上在不同模型中建立關(guān)聯(lián)的方式:// 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條經(jīng)驗 獲得超6個贊
或者您可以使用內(nèi)置的Blue Bird Promise功能來制作它。(致力于Sails@v0.10.5)
請參閱以下代碼:
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來處理數(shù)組。有關(guān)詳細信息,請參閱官方文檔
注意第一個“then”函數(shù)內(nèi)的返回值,數(shù)組中的那些對象“[post,commentUsers]”也是“promise”對象。這意味著它們在首次執(zhí)行時不包含值數(shù)據(jù),直到它們獲得值。因此,“傳播”功能將等待動作值來繼續(xù)做剩下的事情。
- 3 回答
- 0 關(guān)注
- 706 瀏覽
添加回答
舉報
0/150
提交
取消