Search code examples
javascriptmeteormeteor-blazehelper

Retrieve items from mongodb collections if an element of an array is present (meteor js)


I would like to retrieve elements from a collection only if an element in an array is equal to the current month that I have stored in a session. For example, if my session variable is equal to "juillet" I would like to have only the items which have "juillet" in the "moisrec" method :

Legumes = new Mongo.Collection("legumes");

if (Meteor.isServer) {
    Meteor.startup(function() {
      if (Legumes.find().count() === 0) {
            var legumes = [{
                nom: "poireau",
                moisrec: ["juillet", "août"],
            }, {
                nom: "navet",
                moisrec: ["octobre", "novembre"],
            }, {
                nom: "choux-fleur",
                moisrec: ["juillet", "août"]
            }];
            // Insert sample data into db.
            legumes.forEach(function(item) {
                Legumes.insert(item);
            });
       }
    });
}

I have a helpers that looks like this :

Template.Legumes.helpers({
  legumes : function() {
    return Legumes.find({});
  }
});

I use blaze after for templating :

{{#each legumes}}
  <div class="col-sm-3">
      <div class="thumbnail">
        <img src="legumes/{{nom}}.jpg" alt="{{nom}}" width="400" height="300">
         <p><strong>{{nom}}</strong></p>
         <p>Période récolte : {{#each mois in moisrec}}<a>{{mois}} </a>{{/each}}</p>
         <button class="btn" href="/legumes:{{_id}}">Fiche complète</button>
      </div>
   </div>
 {{/each}}

Thanks

Yoann


Solution

  • Legumes.find({ moisrec: "juillet" });
    

    That should get you what you need. Since it's a simple array of strings there isn't any other fancy calls you'll need to make.