在這個(gè)例子中,我們將使用 PlayersCollection 集合有以下數(shù)據(jù)。如果不能確定Meteor中如何創(chuàng)建 MongoDB 集合,您可以查看我們的集合這一章。
C:\Users\Administrator\Desktop\meteorApp>meteor remove autopublish
在此步驟后,你會(huì)發(fā)現(xiàn),無(wú)法從客戶端獲取數(shù)據(jù)庫(kù)中的數(shù)據(jù)。只能在命令提示符窗口中的服務(wù)器端看到它。檢出下面的代碼 -
var PlayersCollection = new Mongo.Collection('playersCollection');
var myLog = PlayersCollection.find().fetch();
console.log(myLog);

比方說(shuō),我們要允許客戶端使用您的數(shù)據(jù)。要允許這一點(diǎn),我們需要在服務(wù)器上創(chuàng)建 Meteor.publish()方法。該方法將數(shù)據(jù)發(fā)送到客戶端。為了能夠接收和使用在客戶端的數(shù)據(jù),我們將創(chuàng)建Meteor.subscribe()方法。在該示例的結(jié)尾,我們檢索的數(shù)據(jù)庫(kù)。這段代碼可以在客戶端和服務(wù)器上運(yùn)行。
var PlayersCollection = new Mongo.Collection('playersCollection');
if(Meteor.isServer) {
Meteor.publish('allowedData', function() {
return PlayersCollection.find();
})
}
if (Meteor.isClient) {
Meteor.subscribe('allowedData');
};
Meteor.setTimeout(function() {
var myLog = PlayersCollection.find().fetch();
console.log(myLog);
}, 1000);

var PlayersCollection = new Mongo.Collection('playersCollection');
if(Meteor.isServer) {
Meteor.publish('allowedData', function() {
return PlayersCollection.find({name: "John"});
})
}
if (Meteor.isClient) {
Meteor.subscribe('allowedData');
};
Meteor.setTimeout(function() {
myLog = PlayersCollection.find().fetch();
console.log(myLog);}, 1000);
