[英]Meteor JS : Client not getting data from Mongo DB
我已经开始学习MeteorJS并制作了一个示例应用程序。 我在mongoDB中有一个集合,我试图在客户端看到该集合这是我的服务器代码(文件在/ libs中)
newColl=new Meteor.Collection("newColl");
if(Meteor.isServer){
Meteor.publish('newCollectionData', function(){
console.log(newColl.find().fetch());
return newColl.find();
});
}
这是我的客户端代码(文件在/客户端)
Meteor.subscribe("newCollectionData");
//console.log(newColl.find());
console.log(newColl.find().fetch());
var data= newColl.find().fetch();
console.log(data);
登录服务器正确打印数据,但登录客户端打印一个空数组。 PS:我已经删除了自动发布,但同时它也给出了相同的结果。 我哪里错了?
Cursor.fetch()
立即返回当前可用的数据。 如果在呼叫期间客户端上没有可用数据,则不返回任何数据。
它是反应源,所以只需尝试在Tracker.autorun
调用它,当反应源发生变化时,它将被重新计算。
Tracker.autorun(function () {
console.log(newColl.find().fetch());
});
如何从html访问Mongo DB中的数据?
首先,您需要将Mongo数据库实例存在于全局变量i中:它必须在任何.js文件中声明,如下所示。 它不是客户端或服务器代码的一部分
假设我们在其中一个js文件中创建了一个事件集合。
EventList = new Mongo.Collection('Events');
现在,为了从HTML访问所有对象,我们需要在.js文件中的客户端内部使用辅助函数。 以下是Helper使用: -
Template.viewEvent.helpers ({
//NOTE : 'event' is the name of variable from html template
'event' : function () {
//returns list of Objects for all Events
return EventList.find().fetch();
}
'users' : function () {
//returns reference to Document for all users
return UserList.find().fetch();
}
});
刚刚离开以显示.html上的所有内容: -
假设EventList Collection包含字段Event_Name,Event_Date。 下面是html模板代码
<template name="viewEvent">
<h2>View Event</h2>
<!-- Iterate on all Objects fetched by the Helper Class-->
{{#each event}}
{{Event_Name}} : {{Event_Date}}
{{/each}}
</template>
试试看
newColl=new Meteor.Collection("newColl");
进入客户端和服务器端,看看它是否有效?
还可以在浏览器控制台中尝试console.log(newColl.find()。fetch()),看看它是否返回任何数据。 如果是,则可能是因为当您打印出newColl.find()。fetch()时数据尚未就绪。
我是meteor.js的新手(也许我错了)。 我认为你需要实现一些方法来观察集合中的变化,以避免在渲染页面时你可以使用流星模板。
如果您只想从客户端查看日志以用于“学习”目的,只需使用浏览器中的客户端控制台即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.