meteor蒙牛没有收集数据
我试图从一个集合中获取文档,但似乎没有工作。
当我使用find()。fetch()时,它只返回一个空数组。 我的代码如下。
var users = new Mongo.Collection("users"); console.log(users.find()); var userRecord = users.find().fetch(); var returnUserRecord = {}; if (userRecord.length >0){ returnUserRecord = {username:userRecord.username, loginHash:userRecord.loginHash}; console.log("if statement is not complete and the value of the return variable is"); console.log(returnUserRecord); } return returnUserRecord
我直接检查了数据库,注意到命令中确实有一个文档集合:
meteor mongo
如果它有任何区别,所有这些代码在服务器js文件中,并从客户端调用:Meteor.Methods()/ Meteor.call()
编辑1
我使用客户端的新数据创build了另一个集合,并在select了正确的数据库并运行以下命令之后:
meteor:PRIMARY> db.newCollection1.find()
我得到:
{ "_id" : ObjectId("55d1fa4686ee75349cd73ffb"), "test1" : "asdasd", "test2" : "dsadsa", "test3" : "qweqwe" }
所以这确认它在数据库中可用,但在客户端控制台中运行以下内容,仍不会返回结果。 (自动发布已安装,我试图删除自动发布,并作出适当的更改订阅表,但也没有工作)。
var coll = new Meteor.Collection('newCollection1'); coll.find().fetch()
这返回一个空的数组。 我也尝试使用相同的server.js代码:
meteor debug
但我仍然得到一个空的数组。 有谁知道我可能在这里做错了吗?
解
解决scheme是在Meteor对象上下文中创build集合variables。 这样可以从Meteor上下文访问。
即
Meteor.coll = new Meteor.Collection('newCollection1'); Meteor.coll.find().fetch();
我希望这可以帮助别人。 取决于你的代码,你可能想使用不同的上下文。
你不等待这个订阅完成,因此你得到空arrays。
你可能应该阅读这个或这个更好地理解它。
关键是你将用户variables连接到“用户”集合,当你调用它时,它还没有被数据污染(如果你不想使用订阅,那么也许使用助手 – 它是被动的,所以它会返回适当的值当subscrtiption完成)
你订阅了你的users
集合吗?
if (Meteor.isServer) { Meteor.publish("users", function(){ Users.find({}) }); } if (Meteor.isClient) { Meteor.subscribe("users"); }
首先是一些build议:你不能两次定义一个集合。 如果您第二次调用new Mongo.Collection("users")
,将会出现错误。 因此,它应该是一个不在方法内的全局variables。
我在你的代码中看到的是,你正在试图使用一个数组,就像它是一个对象。 userRecord.username
不会工作,因为userRecord
具有返回数组的fetch()
的值。
您可以将您的代码更改为userRecord[0].username
或使用forEach
循环结果,如下所示:
var users = new Mongo.Collection("users"); console.log(users.find()); users.find().forEach(function(singleUser){ console.log(EJSON.stringyfy(singleUser)); }
为了返回第一个用户,最好使用findOne
来返回结果中的第一个对象。