3

I need to proceed a collection.find() in another collection. I have a collection named Orders.

Orders = new Mongo.Collection('orders')
Orders.attachSchema(new SimpleSchema({
clientId: {
    type: String
  },
  orderDate: {
    type: Date
  }
});

It uses aldeed:collection2 and aldeed:simple shema. I use it to create a form using aldeed:autoform

I would like to put an allowedValues in the ClientId field that would contain the client ids. So I need to get all clients id with a Clients.find(). Clients is another collection. But on the client if I try to put console.log(Clients.find().fetch()) in my order.js collection file, it logs an empty array while on the server it logs an array containing all my clients. I unterstand that the call to the function is made before the collection is available by the client. But even wrapping it in a Meteor.startup doesn't work. Does someone have a clue?

yves
  • 33
  • 2

2 Answers2

1

I guess what you are trying to do is limit the selection of client in the Order editor. You can create a helper like following

Template.editOrder.helpers
   clientList: ()->
     Client.find().fetch()

And use this helper with autoform

{{> afQuickField name="clientSelected" options=clientList}}
Ryan Wu
  • 5,963
  • 2
  • 36
  • 47
0

Actually, it was quite tricky to get all this together because I also needed to validate the field on the client side. So I used the solution shown by Ryan but needed to add some stuff:

var ordersShema = {
clientId: {
    type: String,
    allowedValues: clientsId
  },..
}

Orders.attachSchema(new SimpleSchema(ordersShema));

with clientsId beeing the ids that where dynamically uploaded from the Clients collection. But this is ok on the server side but on the client side, clientsId was still empty and the validation wasn't possible. So I had to add this code on the client side:

Tracker.autorun(function () {
  Orders._c2._simpleSchema._schema.clientId.allowedValues = Labelizer.allowedValues(Clients.find(),'_id');
});

(Labelizer is just a function to create the allowedValues from a cursor).

And of course, the options are generated with a helper.

Template.ordersAdd.helpers({
  clientsList:function(){
    return Labelizer.options(Clients.find(),'_id',['name','surname'],' ');
  },...
}

So the field works great with this helper:

{{> afQuickField name='clientId' options=clientsList}}
yves
  • 33
  • 2