无法让meteor.js返回mongo集合

时间:2022-01-06 17:06:47

So I am trying to return a mongoDB database value to a template in my Meteor.js project. The code that I am using is below.

所以我试图将mongoDB数据库值返回到Meteor.js项目中的模板。我正在使用的代码如下。

Template.ResourceManager.helpers({
BoosterOneFuel : function(){
        return resources.findOne({system : "booster1"}).fuel;
}

});

However, this always returns null. When I try to alert it, the alert also says that this value is null. Mongo can find it when I run this line in the console while running meteor mongo:

但是,这始终返回null。当我尝试提醒它时,警报还会说该值为空。当我在运行meteor mongo时在控制台中运行此行时,Mongo可以找到它:

db.Resources.findOne({system : "booster1"}).fuel;

But meteor cannot. (This is on a localhost, so meteor mongo should affect meteor's database)

但流星不能。 (这是在本地主机上,因此meteor mongo会影响meteor的数据库)

I don't think its a problem with meteor loading before mongo does, because the following still doesn't work :

在mongo之前我不认为它是流星加载的问题,因为以下仍然不起作用:

if(resource.find({system : "booster1"}))
     alert(resources.findOne({system : "booster1"}).fuel);

Anybody know whats going on here? Thanks in advance.

有谁知道这里发生了什么?提前致谢。

1 个解决方案

#1


Assuming the collection is actually called resources - i.e. you have something that looks like:

假设集合实际上被称为资源 - 即你有一些看起来像:

resources = new Mongo.Collection('Resources');

Then it sounds like you just need to publish the documents to the client:

然后听起来你只需要将文档发布到客户端:

server/publishers.js

Meteor.publish('resources', function() {
  return resources.find();
});

client/subscriptions.js

Meteor.subscribe('resources');

Of course the subscription could happen in your template or router instead of globally, but that's beyond the scope of this question.

当然订阅可能发生在你的模板或路由器而不是全局,但这超出了这个问题的范围。

Also note you should add a guard to your helper. For example:

另请注意,您应该为助手添加一名警卫。例如:

Template.ResourceManager.helpers({
  BoosterOneFuel : function() {
    var b1 = resources.findOne({system : "booster1"});
    return b1 && b1.fuel;
  }
});

#1


Assuming the collection is actually called resources - i.e. you have something that looks like:

假设集合实际上被称为资源 - 即你有一些看起来像:

resources = new Mongo.Collection('Resources');

Then it sounds like you just need to publish the documents to the client:

然后听起来你只需要将文档发布到客户端:

server/publishers.js

Meteor.publish('resources', function() {
  return resources.find();
});

client/subscriptions.js

Meteor.subscribe('resources');

Of course the subscription could happen in your template or router instead of globally, but that's beyond the scope of this question.

当然订阅可能发生在你的模板或路由器而不是全局,但这超出了这个问题的范围。

Also note you should add a guard to your helper. For example:

另请注意,您应该为助手添加一名警卫。例如:

Template.ResourceManager.helpers({
  BoosterOneFuel : function() {
    var b1 = resources.findOne({system : "booster1"});
    return b1 && b1.fuel;
  }
});