【发布时间】:2014-02-19 01:57:36
【问题描述】:
我正在使用一些表单输入来创建一个新的Student,代码如下:
var student_id = Students.insert({firstname: firstInput, lastname: lastInput, price: priceInput});
Meteor.users.update({_id: Meteor.userId()}, {$push: {'student_ids': student_id}});
我设置了以下订阅和发布:
// On the client.
Meteor.subscribe('currentUser');
// On the server.
// I know this is ugly, but I need to do quite a bit of joining.
Meteor.publish('currentUser', function() {
if (!this.userId) return;
var userCursor = Meteor.users.find({_id: this.userId}, { fields: {firstname: true, lastname: true, student_id: true, student_ids: true, payment_ids: true, phones: true }});
var user = userCursor.fetch()[0];
if (user.student_ids || user.payment_ids) {
var student_ids = user.student_ids || [];
var studentCursor = Students.find({_id: {$in: student_ids}});
var payment_ids = user.customer.payment_ids || [];
var paymentCursor = Payments.find({_id: {$in: payment_ids}});
var lesson_ids = [];
var expense_ids = [];
studentCursor.forEach(function(doc) {
lesson_ids.concat(doc.lesson_ids);
expense_ids.concat(doc.expense_ids);
});
var lessonCursor = Lessons.find({_id: {$in: lesson_ids}});
var expenseCursor = Expenses.find({_id: {$in: expense_ids}});
return [userCursor, studentCursor, lessonCursor, expenseCursor, paymentCursor];
}
else return userCursor;
});
问题是我的{{#each}} 块之一列出了所有这些学生,并且工作正常,除了在页面刷新/重新启动等之前它不会显示新学生。发布/订阅对没有反应。
我不确定如何优雅地解决这个问题。我绝对不想在发布函数中使用added 和其他此类回调。看来我的收藏应该自己处理这种行为。
提前致谢!
更新
我将发布更改为使用 publish-with-relations,这是一个反应式连接包,现在看起来像这样:
Meteor.publish('currentUser', function() {
var studentMappings = [{
key: 'lesson_ids',
collection: Lessons,
},{
key: 'expense_ids',
collection: Expenses,
}];
return Meteor.publishWithRelations({
handle: this,
collection: Meteor.users,
filter: this.userId,
options: { fields: {firstname: true, lastname: true, student_id: true, student_ids: true, payment_ids: true, phones: true }},
mappings: [{
key: 'student_id',
collection: Students,
mappings: studentMappings
},{
key: 'student_ids',
collection: Students,
mappings: studentMappings
},{
key: 'payment_ids',
collection: Payments,
}]
});
});
所有内容都已发布,但仍不是反应式的!当页面重新加载时,一切都如预期的那样,但在添加新学生后,该学生所在的位置只会闪烁(我怀疑这是工作中的延迟补偿)。
当我在控制台查询Meteor.user()时,student_ids数组是正确的:
student_ids: Array[1]
0: "5dafpCD7XGcBnyjWd"
length: 1
当我meteor mongo这个时:
meteor:PRIMARY> db.students.find()
{ "firstname" : "Sterling", "lastname" : "Archer", "price" : "22.50", "_id" : "5dafpCD7XGcBnyjWd" }
一切也都是正确的,但在页面刷新之前文档仍然没有显示。
publish-with-relations 不是应该解决这个问题吗?
【问题讨论】:
标签: meteor