[英]Meteor & MongoDB. Troubles with getting data from collection (finding documents between two dates)
[英]Having troubles with getting data from Meteor collection
有人可以向我解釋一下嗎:如果我正在瀏覽器的控制台中從集合中獲取數據,則可以正常工作,但同時呈現模板(使用相同集合)時,它會引發異常,如查詢結果為空。 我究竟做錯了什么?
Hubs = new Meteor.Collection("hubs");
Meteor.subscribe("hubs");
Template.thread.posts = function() {
var hubName = 'foo',
thread = Session.get("currentThread"),
hub = Hubs.find({ name: hubName }).fetch()[0];
//throws: "Uncaught TypeError: Cannot read property 'threads' of undefined "
return hub.threads[thread].posts;
}
//this being executed in browser's console yeilds an object:
Hubs.find({name: 'foo'}).fetch()[0]
盡管使用相同集合的其他模板也可以正常工作
當Meteor最初在瀏覽器上加載時,它不會再包含來自服務器的集合中的數據。
它們僅需很短的時間即可使用。 因此,您只需要處理沒有提供結果的情況。 數據到達后,反應性應使用新數據更新所有模板。
您可以使用類似:
hub = Hubs.findOne({ name: hubName })
if(hub) return hub.threads[thread].posts;
findOne
是find().fetch[0]
。 因此,如果沒有結果,即null
, .threads
不會返回任何內容, .threads
不會讀取.threads
因此不會出現異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.