javascript - 在 Meteor Web 应用程序中显示多维数据库文档

标签 javascript html mongodb meteor

我决定在我当前的 Web 应用程序项目中使用 Meteor。在此网站上,我们希望用户拥有自己的汽车库存,并需要使用 Meteor 的 Sidebars 模板引擎以以下格式显示 Mongo Collection 中的汽车。

Car 1
    Engine: 6-cylinder
    Color: black
Car 2
    Engine: 4-cylinder
    Color: white

我们的模板设置如下:

<template name=”cars”>
    {{#each cars}}
        {{> car}}
    {{/each}}
</template>

<template name=”car”>
    Engine: {{engine}}
    Color: {{color}}
</template>

我们的 helper :

Template.cars.helpers({
    return Cars.find({ownerId: Meteor.user_id()});
});

Template.car.helpers({
    engine: function(){
        var car_id = “???”;
        return Car.findOne({car_id: car_id}).engine;
     },

    color: function(){
        var car_id = “???”;
        return Car.findOne({car_id: car_id}).color;

    },
});

我的问题是将 car_id 传递给辅助函数。我知道我们可以通过模板上的 data 属性将参数传递给辅助函数,例如 {{car data=carId}} 但随后我们需要从 Template 传递 car_id。 cars.helpers

是否有一种我没有看到的简单方法可以实现此目的,或者我是否误解了 Meteor 和 Sidebars 的基本原理?

注意:实际应用与汽车无关,也没有这么简单。因此,需要有单独的 Mongo Collections 来保存 Cars 和 Car 属性。

最佳答案

当您使用#each迭代游标时,内部上下文将成为单个文档。在您的示例中,car 模板具有汽车文档的上下文。因此,渲染 {{engine}}{{color}} 不需要助手。

为了更好地理解这一点,我建议阅读 A Guide to Meteor Templates & Data Contexts .

但是,如果您需要助手内汽车的 _id 才能执行其他操作(可能是集合连接),那么您可以通过 this 访问它。 _id (同样,此示例中的帮助程序的上下文是文档)。这是一个例子:

Template.car.helpers({
  driver: function() {
    return Meteor.users.findOne({carId: this._id});
  }
});

关于javascript - 在 Meteor Web 应用程序中显示多维数据库文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30295437/

相关文章:

php - 文本区域中的换行符

javascript - 在两个 meteor 模板之间推送数据

javascript - 如何以编程方式访问 NodeJS 异常文本

javascript - css 和 js 无法在 Rails 生产模式下工作

javascript - 为什么不能通过 "data execution prevention"修复 Javascript shellcode 漏洞?

html - zen coding 还能回到之前的水平吗?

html - 独立滚动的 div,一个带有固定的页眉和页脚

mongodb - mongodb 中的子查询

mongodb - 使用 mongoimport 将 csv 数据作为数组导入 mongodb

javascript - Mouseenter 内部的函数不改变 Attr