代碼:爲什麼下面的Meteor/mongodb findOne返回undefined?
Template.chapterForm.rendered = ->
Meteor.startup ->
currentChapter = Chapters.findOne(
_id: "Wdyxj8pWg2HPzuDuf"
)
console.log currentChapter
console.log currentChapter.content
我得到以下輸出:
undefined
Exception from Tracker afterFlush function: Cannot read property 'content' of undefined TypeError:
Cannot read property 'content' of undefined
我不解。它是CoffeScript錯誤還是Meteor/mongodb錯誤?
(我試過的代碼移動到文件的頂部仍然得到不確定的。)
編輯:
奇怪,如果我做
Chapters.findOne({_id: "Wdyxj8pWg2HPzuDuf"});
在我做的控制檯獲取對象:
Object
發生這種情況是因爲在第一頁上呈現數據並未到達客戶端,因此該集合爲空。稍後,websocket連接將獲取剩餘的數據,並且調用返回一個對象。 – imslavko 2014-10-12 04:23:12
這是流星編程中最常見的陷阱之一。請參閱[本文](https://dweldon.silvrback.com/guards)獲取完整的解釋和解決方案。 – 2014-10-12 04:37:00
[Meteor findOne query可能重複在一個模板助手中返回undefined。在其他模板助手中,相同的查詢效果不錯](http://stackoverflow.com/questions/17728386/meteor-findone-query-returns-undefined-in-one-template-helper-in-other-template) – 2015-03-26 00:41:14