简体   繁体   中英

Cannot access a collection in Angular-Meteor

I am trying to work with data from a Collection in Angular-Meteor, but so far I fail to access it.

In lib/collections.js I define the collection:

UserMeta = new Mongo.Collection('userMeta');

server/publish.js publishes it:

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

and in my client code client/scripts/controllers/settings.controller.js I subscribe:

angular
  .module('App')
  .controller('SettingsCtrl', SettingsCtrl);

function SettingsCtrl($scope, $reactive) {
  $reactive(this).attach($scope);
  this.subscribe('userMeta');
  //...
}

I have discovered that there seem to be multiple ways to subscribe (even used inconsistently in the official tutorial from Angular-Meteor), but I have decided to use the most recent syntax for v.1.3.2: Subscribe API

But if I want to view the whole content of the collection, it returns an empty array:

console.log(UserMeta.find().fetch()); // =[]

Or:

console.log(UserMeta.findOne()); // =undefined

However, if I run these commands in the client console in my browser, the expected results are returned.

Can somebody please give me a short example, how I can work with my collections? I am used to the way (pure) Meteor handles this and am confused that it does not seem to be as simple in Angular-Meteor.

Try using

Meteor.Methods

On your Server side call

Meteor.methods({
getUserMeta: function () {
 var data = UserMeta.find({}).fetch();
 return data;
}

All call this method on server side using

 Meteor.call('getUserMeta',function (err, data) {
   if (!err) {
     Console.log(data);
   } else {
     console.log("error");
   }
});

When you use Collection in console.log it isn't ready yet and hasn't any data. You can use console.log inside helpers or you should check if collection is ready like this:

// Client-side
var subs = Meteor.subscribe('lastMsgRead', Meteor.userId());
Meteor.autorun(function() {
  if (subs.ready()) { ... }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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