【问题标题】:Handlebars {{#each}} helper displaying wrong amount of values that i get from Mongoose.model.find()Handlebars {{#each}} 助手显示我从 Mongoose.model.find() 获得的错误数量的值
【发布时间】:2022-02-17 08:45:26
【问题描述】:

当我尝试在我的 list.handlebars 上使用 {{#each}} 时,它会在显示我的内容填充数据之前在 {{#each}} 中显示 2 个内容,我试图弄清楚发生了什么,但从所有我一直在研究,我没有看到任何解决方案。

这是我的代码的相关部分:

app.js(主要代码):

app.get("/lista/:arvores", (req, res) => {
    if (req.params.arvores === "arvoresnativas") {
        db.nativas.find().then((dataArvoresNativas) => {
            dataArvoresNativas.forEach((findArvoresNativas) => {
                console.log(findArvoresNativas);
                res.render("lista.handlebars",
                    {
                        findArvNativas: findArvoresNativas,
                        strArv: stringArvoresNativas,
                    }
                );
            });
        });
    }
});

list.handlebars

<h1>Lista de {{strArv}}</h1>

{{#each findArvNativas}}
    <h2>Nome: {{nome}}</h2>
    <h2>Nome científico: {{nomecientifico}}</h2>
    <h2>Ordem: {{ordem}}</h2>
    <h2>Origem: {{origem}}</h2>
{{/each}}

这里是 mongo.js,我将 Moongoose.model() 导出到我的国家的本地和外来树种的 mongoose 连接(我是巴西人,对不起 var 名称,我希望有人能理解我的代码):

mongo.js

const mongoose = require("mongoose");

mongoose
    .connect("mongodb://localhost/mongodatabase", {
        useNewUrlParser: true,
    })
    .then(() => console.log("Conectado ao MongoDB!"))
    .catch((error) => console.log("Erro ao tentar se conectar ao MongoDB: " + error));

const arvores = mongoose.Schema({
    nome: {
        type: String,
        require: true,
    },

    nomecientifico: {
        type: String,
        require: true,
    },

    ordem: {
        type: String,
        require: true,
    },

    origem: {
        type: String,
        require: true,
    },
});

const arvoresnativas = mongoose.model("arvoresnativas", arvores);
const arvoresexoticas = mongoose.model("arvoresexoticas", arvores);

module.exports = {
    nativas: arvoresnativas,
    exoticas: arvoresexoticas,
};

当我访问 http://localhost:3031/lista/arvoresnativas 时,这就是我的输出:

但是当我执行 db.arvoresnativas.find() 时会看到 mongo 查询显示的内容:

我尝试删除表格并重新定义它,我也尝试了几乎所有方法,但我是初学者,除了谷歌搜索之外,我无能为力。

【问题讨论】:

    标签: javascript node.js mongodb mongoose handlebars.js


    【解决方案1】:

    您不想遍历数据并执行 Handlebars 文件的单个 renders。您目前正在这里执行此操作:

    dataArvoresNativas.forEach((findArvoresNativas) => {
      // You should only call this once, you currently are calling it for every
      // `findArvoresNativas` you have
      res.render(/* ... */);
    });
    

    我的猜测是,这意外地影响不大,因为您的 find 操作仅返回一项,因此您的 forEach 循环仅执行一次。

    因此,当您进行渲染时,您将发送一个 Object 作为您的 findArvNativas 变量,然后您使用内置的 each 方法对其进行迭代。 Handlebars 的each 迭代对象中的键/值对,这似乎不是您想要的。

    相反,只需使用 dot notation 访问您的 findArvNativas 对象上的嵌套属性。

    <h1>Lista de {{strArv}}</h1>
    
    <h2>Nome: {{findArvNativas.nome}}</h2>
    <h2>Nome científico: {{findArvNativas.nomecientifico}}</h2>
    <h2>Ordem: {{findArvNativas.ordem}}</h2>
    <h2>Origem: {{findArvNativas.origem}}</h2>
    

    如果您不想每次访问属性时都输入findArvNativas,可以使用with 帮助器设置新的上下文。

    <h1>Lista de {{strArv}}</h1>
    
    {{#with findArvNativas}}
        <h2>Nome: {{nome}}</h2>
        <h2>Nome científico: {{nomecientifico}}</h2>
        <h2>Ordem: {{ordem}}</h2>
        <h2>Origem: {{origem}}</h2>
    {{/with}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多