I have created a mongoDB collection through server code in meteor:
我通过meteor中的服务器代码创建了一个mongoDB集合:
//Server
Restaurants = new Mongo.Collection('restaurants')
if (Meteor.isServer) {
//This code only runs on the server
Meteor.publish('restaurants', function () {
return Restaurants.find();
});
}
I am trying to fetch latest data on client side every time when the data changes in the database.
每次数据库中的数据发生变化时,我都会尝试在客户端获取最新数据。
This is my client side code:
这是我的客户端代码:
//Client
Restaurants = new Mongo.Collection('restaurants');
var myData = "";
if (Meteor.isClient) {
Meteor.subscribe('restaurants');
myData = Restaurants.find();
};
Thanking you!
1 个解决方案
#1
1
For completeness, here's a quick revised example using your code that shows how Tracker
works.
为了完整起见,这里有一个快速修改的示例,使用您的代码显示Tracker的工作原理。
Restaurants = new Mongo.Collection('restaurants')
if (Meteor.isClient) {
Meteor.subscribe('restaurants');
Tracker.autorun(() => {
const restaurant = Restaurants.findOne();
console.log(restaurant);
});
};
if (Meteor.isServer) {
Meteor.publish('restaurants', function restaurants() {
return Restaurants.find();
});
Meteor.startup(() => {
if (Restaurants.find().count() === 0) {
Restaurants.insert({
name: 'McDonalds',
});
}
});
}
The above will first log undefined
to your console since when Restaurants.findOne
is first called, no restaurant data has been pushed to the client yet. By wrapping your find in a Tracker.autorun
, when restaurant data is pushed to the client, your find will re-run, and the loaded restaurant will be logged to the console. So your console output will look like:
以上将首先将undefined记录到您的控制台,因为首次调用Restaurants.findOne时,尚未将任何餐馆数据推送到客户端。通过将您的查找包装在Tracker.autorun中,当餐馆数据被推送到客户端时,您的查找将重新运行,并且已加载的餐馆将被记录到控制台。所以你的控制台输出看起来像:
undefined
Object {_id: "HAJpQxfq59KPmTwDA", name: "McDonalds"}
#1
1
For completeness, here's a quick revised example using your code that shows how Tracker
works.
为了完整起见,这里有一个快速修改的示例,使用您的代码显示Tracker的工作原理。
Restaurants = new Mongo.Collection('restaurants')
if (Meteor.isClient) {
Meteor.subscribe('restaurants');
Tracker.autorun(() => {
const restaurant = Restaurants.findOne();
console.log(restaurant);
});
};
if (Meteor.isServer) {
Meteor.publish('restaurants', function restaurants() {
return Restaurants.find();
});
Meteor.startup(() => {
if (Restaurants.find().count() === 0) {
Restaurants.insert({
name: 'McDonalds',
});
}
});
}
The above will first log undefined
to your console since when Restaurants.findOne
is first called, no restaurant data has been pushed to the client yet. By wrapping your find in a Tracker.autorun
, when restaurant data is pushed to the client, your find will re-run, and the loaded restaurant will be logged to the console. So your console output will look like:
以上将首先将undefined记录到您的控制台,因为首次调用Restaurants.findOne时,尚未将任何餐馆数据推送到客户端。通过将您的查找包装在Tracker.autorun中,当餐馆数据被推送到客户端时,您的查找将重新运行,并且已加载的餐馆将被记录到控制台。所以你的控制台输出看起来像:
undefined
Object {_id: "HAJpQxfq59KPmTwDA", name: "McDonalds"}