Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I populate a dropdown menu with Mongodb in Meteor javascript?

is there a way I can populate a dropdown list with values stored in Mongodb? For example, if I have a car object that has a color attribute that could contains values: black', 'red or blue, I want the dropdown list to contain those values. I need to do this in Meteor javascript.

Thank you.

like image 410
Trung Tran Avatar asked Jun 23 '15 11:06

Trung Tran


2 Answers

without any dependencies you can do simply

<select name="sss">
 {{#each colors}}
    <option>{{this}}</option>
{{/each}}
</select>

Template.mytemplate.helpers({
   colors: function(){
    return Colors.find().map(function (doc) {
      return doc.name
    })
 }
});
like image 127
Sasikanth Avatar answered Sep 20 '22 20:09

Sasikanth


Easiest and cleanest way is to use aldeed:autoform. autoform relies on aldeed:simple-schema and collection2. With these packages you can do this:

Cars = new Mongo.Collection('Cars')

Cars.attachSchema({
  color: {
    type: String,
    allowedValues: ['red', 'black', 'green']
  }
})

Now let's assume you have a collection called Colors and all these documents have a value name:

function getColors () {
  return Colors.find().map(function (doc) {
    return doc.name
  })
}

Cars.attachSchema({
  color: {
    type: String,
    allowedValues: getColors()
  }
})
like image 39
halbgut Avatar answered Sep 20 '22 20:09

halbgut