【问题标题】:Meteor query runs perfectly fine on server but not on clientMeteor 查询在服务器上运行得非常好,但在客户端上却不行
【发布时间】:2021-04-16 11:53:53
【问题描述】:

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

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”,这是预期的输出并且很棒。
我在这里遗漏了什么?
编辑:我还安装了自动发布功能,我不期待删除它,因为这个软件无论如何都是一个测试。

【问题讨论】:

    标签: meteor meteor-blaze meteor-collections


    【解决方案1】:

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

    【讨论】:

    • 好吧,我想我需要阅读更多关于流星反应性的信息。但是非常感谢!使用流星可选链接也是不错的建议。我找不到该功能,然后改用 lodash :D 谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 2014-09-16
    • 2022-10-26
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    相关资源
    最近更新 更多