使用 Meteor 从 Mongo 获取 json

Fetching json from Mongo with Meteor

我正在尝试使用流星从 mongodb 中获取 json 对象,但我不知道为什么我无法这样做。

我只需要它是一个 JSON 对象。

集合中的一个条目如下所示:

[图片取自 Meteor Dev Tools]

Link: https://i.stack.imgur.com/BxRmS.png

我正在尝试通过传递 name 来获取 value 部分。

前端代码:

export default withTracker(() => {
  let aSub = Meteor.subscribe(‘allEntries’);
  return {
    aBoundaries: DataCollection.find({}).fetch()    
   }
})(Component Name);

前端的Meteor调用语句: dataFromDb = Meteor.call(‘functionToBeCalled’, ‘悉尼’);

服务器端代码:

Meteor.publish(‘allEntries’, function(){
    return DataCollection.find();
});

Meteor.methods({
   functionToBeCalled(aName){
      return DataCollection.find({name: aName});
   }
});

我的另一个问题是: 有没有办法一开始只发布所有名字,然后按需发布值?

提前感谢您的帮助!

我也试过了,但是没用:

functionToBeCalled(aName){
        var query = {};    
        query['name'] = aName;
        return DataCollection.find(query).fetch();
}

问题似乎与查询有关。

Collection.find() returns 有光标的数据。

要获取对象数组,请使用 Collection.find().fetch()。 json 被 return 编辑为数组集合,如 [{json1}, {json2}]

如果只有一个文档,您可以使用 Collection.find().fetch()[0] 访问 json。另一种选择是使用 findOne。示例 - Collection.findOne()。这将 return 一个 JSON 对象。

使用Meteor.subscribe('allEntries'),不要将其赋值给变量。

Meteor.subscribe 是异步的,最好在获取数据之前确保订阅已准备就绪。

DataCollection.find({}).fetch() 记录到您的控制台

查看此官方参考资料 https://docs.meteor.com/api/pubsub.html#Meteor-subscribe

你的第二个问题不是很清楚。

万一有人来找答案呢~~~ 所以...我能够让它在服务器上使用此代码:

Meteor.methods({
    functionToBeCalled(aName){
        console.log(aName);
        return DataCollection.findOne({name: aName});
    }     
});

在客户端上:

Meteor.call('functionToBeCalled', nameToBePassed, (error,response) => {
            console.log(error, "error");
            console.log(response, "response"); //response here
})

感谢您的帮助!