meteormeteor-blazemeteor-collections

Meteor query runs perfectly fine on server but not on client


So I have a simple server file:

import { Meteor } from 'meteor/meteor';

const Animals = new Mongo.Collection("animals");

let animalsFindOne = Targets.findOne({animal: "henry"});
console.log(_.get(animalsFindOne, 'food.favorite.amount'));

And a animals.js file that renders to the template

import {Template} from "meteor/templating";
import {Mongo} from "meteor/mongo";

import "/imports/ui/targets/animals.html";

const Animals = new Mongo.Collection("animals");
let animalsFindOne = Targets.findOne({animal: "henry"});

Template.targets.helpers({
    foodAmount: function() {
        return _.get(animalsFindOne, 'food.favorite.amount';
    }
});

I could return "foo" as foodAmount and the template would render it perfectly fine. For _.get I use erasaur:meteor-lodash, which works perfectly fine in server.js. In the server console the output is "5", the output that is expected and great.
What piece am I missing here?
Edit: Also I have autopublish installed, and I am not looking forward to removing it, as this software is a test anyways.


Solution

  • The animalsFindOne is already defined outside the foodAmount helper, thus it won't trigger the Template's reactivity-based redrawing mechanism.

    In order to gain reactivity in helpers you need to call queries within the helper:

    import {Template} from "meteor/templating";
    import {Mongo} from "meteor/mongo";
    
    import "/imports/ui/targets/animals.html";
    
    const Animals = new Mongo.Collection("animals");
    
    
    Template.targets.helpers({
        foodAmount: function() {
            let animalsFindOne = Targets.findOne({animal: "henry"});
            return _.get(animalsFindOne, 'food.favorite.amount';
        }
    });
    

    edit: Meteor allows optional chaining with the more recent versions, so no need for lodash here:

    Template.targets.helpers({
        foodAmount: function() {
            let animalsFindOne = Targets.findOne({animal: "henry"});
            return animalsFindOne?.food?.favorite?.amount
        }
    });