繁体   English   中英

流星蒙哥未获取收集数据

[英]Meteor Mongo Not Getting Collection Data

我正在尝试从集合中获取文档,但是它似乎没有用。

当我使用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

我选择了正确的数据库并运行以下命令后,从客户端使用新数据创建了另一个集合:

meteor:PRIMARY> db.newCollection1.find()

我得到:

{ "_id" : ObjectId("55d1fa4686ee75349cd73ffb"), "test1" : "asdasd", "test2" : "dsadsa", "test3" : "qweqwe" }

因此,这确认它在数据库中可用,但是在客户端控制台中运行以下命令仍不会返回结果。 (安装了autopublish。我尝试删除autopublish,并进行了适当的更改以订阅该表,但这也不起作用)。

var coll = new Meteor.Collection('newCollection1');
coll.find().fetch()

这返回一个空数组。 我也使用以下方法在server.js代码上尝试了相同的操作:

meteor debug

但我仍然得到一个空数组。 有人知道我在这里可能做错了吗?

解决方案是在Meteor对象上下文中创建collection变量。 这样就可以从流星上下文中访问它。

Meteor.coll = new Meteor.Collection('newCollection1');
Meteor.coll.find().fetch();

我希望这可以帮助别人。 根据您的代码,您可能希望使用其他上下文。

您无需等待此订阅完成,因此会得到空数组。

您可能应该阅读此书此书,以更好地理解它。

关键是将users变量连接到“ users”集合,并且在调用它时,它尚未被数据污染(如果您不想使用订阅,则可以使用helper-它是反应性的,因此它将返回正确的值订阅结束后)

您是否在某个地方订阅了users收藏集?

if (Meteor.isServer) {
  Meteor.publish("users", function(){
     return Users.find({})
  });
}

if (Meteor.isClient) {
  Meteor.subscribe("users");
}

首先一些建议:不能两次定义一个集合。 如果第二次调用new Mongo.Collection("users") ,则会收到错误消息。 因此,它应该是全局变量,而不是方法内部。

我在您的代码中看到的是,您试图像使用对象一样使用数组。 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返回结果中的第一个对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM