代码:
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
最佳答案
以下两个表达式在coffeescript中完全相同
章节.findOne( _id:“Wdyxj8pWg2HPzuDuf” )
Chapters.findOne({_id: "Wdyxj8pWg2HPzuDuf"})
我不知道你为什么在模板实例中使用“Meteor.startup ->”,这不是好方法。在 Meteor docs ,“在客户端上,一旦 DOM 准备好,该函数就会运行。”因此 findOne 操作将在屏幕创建或渲染后立即运行。我认为它可能会破坏模板实例生命周期顺序,因此只需使用“创建”和“渲染”周期。
此外,从 #2 开始,从生命周期开始,您应该在获取集合 (findOne) 之前订阅该集合,位于父模板或路由器代码中的某个位置。
所以结论是你的浏览器mini-mongo中似乎没有数据。 这意味着您需要使用 'Chapters.find().fetch()' 命令检查浏览器控制台,然后如果您可以在控制台上看到数据但仍然出现相同的错误,则应该检查生命周期以进行明确订阅。
关于javascript - 为什么以下 Meteor/mongodb findOne 返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26321600/