Meteor 查询在服务器上运行得非常好,但在客户端

问题描述

所以我有一个简单的服务器文件

import { Meteor } from 'meteor/meteor';

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

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

以及呈现到模板的 animals.js 文件

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';
    }
});

我可以将 "foo" 作为 foodamount 返回,模板会完美呈现它。对于 _.get,我使用 erasaur:meteor-lodash,它在 server.js 中运行良好。在服务器控制台中,输出为“5”,这是预期且很棒的输出
在这里遗漏了什么?
编辑:我也安装了自动发布,我不期待删除它,因为这个软件无论如何都是一个测试。

解决方法

animalsFindOne 已经在 foodAmount 助手之外定义,因此它不会触发模板的基于反应性的重绘机制。

为了在助手中获得反应性,您需要在助手中调用查询:

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';
    }
});

编辑:Meteor 允许 optional chaining 使用更新的版本,所以这里不需要 lodash:

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