简体   繁体   English

Pug/Node.Js:无法读取未定义的属性“长度”

[英]Pug/Node.Js: Cannot read property 'length' of undefined

I searched for hours and hours without solving this problem.我搜索了几个小时都没有解决这个问题。 I'm a very beginner in Node.Js, and I'm currently using it with Express along with Router and Sequelize for a school project.我是 Node.Js 的初学者,目前我正在将它与 Express 以及 Router 和 Sequelize 一起用于学校项目。

Context:语境:

I have a MySQL database with a table "products" and two rows: http://i.imgur.com/U5Lqtpo.png我有一个 MySQL 数据库,其中有一个表“产品”和两行: http://i.imgur.com/U5Lqtpo.png

I want to display each id, libelle, type, description and ean13Code for each SQL row.我想显示每个 SQL 行的每个 id、libelle、类型、描述和 ean13Code。

Problem:问题:

I'm unable to pass the result of a "findAll()" query into the Pug template.我无法将“findAll()”查询的结果传递到 Pug 模板中。 I'm constantly faced with this error which is: Cannot read property 'length' of undefined .我经常遇到这个错误: Cannot read property 'length' of undefined

Code samples:代码示例:

Below are the code samples.以下是代码示例。 I hope someone will be able to know what's going on as I have no clue why it isn't working.我希望有人能够知道发生了什么,因为我不知道为什么它不起作用。

Let me know if I forgot to mention something important.如果我忘记提及重要事项,请告诉我。

products.pug产品.pug

extends layout

block body
center
  h1= title
  p Welcome to #{title}

  ul
    each product in list_products //<-- Cannot read property 'length' of undefined
      li= item.libelle

app.js应用程序.js

'use strict';

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var models = require('./models');
var index = require('./routes/index');
var sign_in = require('./routes/sign_in');
var users = require('./routes/users');
var products = require('./routes/products');

var app = express();
models.sequelize.sync({
  //force: true
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
//app.use('/sign_In', sign_in);
app.use('/users', users);
app.use('/products', products);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Route Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

index.js (route) index.js(路线)

var express = require('express');
var router = express.Router();

/* GET index page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'my title' });
});

/* GET sign page. */
router.get('/sign_in', function(req, res, next) {
  res.render('sign_in', { title: 'my title' });
});

/* GET users page. */
router.get('/users', function(req, res, next) {
  res.render('users', { title: 'my title' });
});

/* GET products page. */
router.get('/products', function(req, res, next) {
  res.render('products', { title: 'my title' });
});

module.exports = router;

products.js (route) products.js(路线)

"use strict";

const express = require("express");
const models = require("../models");
const router = express.Router();
const Product = models.Product;

router.post("/", function(req, res, next){
    let libelle = req.body.libelle;
    let type = req.body.type;
    let description = req.body.description;
    let ean13Code = req.body.ean13Code;
    Product.create({
        libelle: libelle,
        type: type,
        description: description,
        ean13Code: ean13Code
    }).then(function(prod){
        res.json(prod);
    }).catch(next);
});

router.get("/", function(req,res,next){
    let limit = req.query.limit || 20;
    let offset = req.query.offset || 0;

    let options = {
        limit: limit,
        offset: offset
    }

    let search = req.query.search;
    if(search) {
        let where = {
            $or: {
                libelle: {
                    $like: "%" + s + "%"
                },
                type: {
                    $like: "%" + s + "%"
                },
                ean13Code: {
                    $like: "%" + s + "%"
                }
            }
        }
        options.where = where;
    }

    Product.findAll().then(function(products){
        for(let i in products){
            products[i] = products[i].responsify();
        }
        // I want to send the results of the findAll() to the products.pug page
        res.render("/", {list_products: products});
    }).catch(next);
});


router.get("/:prod_id", function(req,res, next){
    Product.find({
        where: { id: req.params.prod_id },
        include: [ models.Product ]
    }).then(function(prod){
        res.json(prod);
    }).catch(next);
});

module.exports = router;

product.js (model) product.js(模型)

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Product = sequelize.define('Product', {
    id: { type: DataTypes.BIGINT, primaryKey: true, autoIncrement: true },
    libelle: { type: DataTypes.STRING, allowNull: false },
    type: { type: DataTypes.STRING, allowNull: false },
    description: { type: DataTypes.STRING, allowNull: true },
    ean13Code: { type: DataTypes.STRING, unique: true, allowNull: true }
  }, {
    paranoid: true,
    underscored: true,
    freezeTableName: true
  });
  return Product;
};

From the comments: 来自评论:

It seems Sequelize doesn't appreciate a return like I did in the product model. 似乎Sequelize并不像我在产品模型中那样欣赏回报。 I had to do something like this : return sequelize.define([...]); 我不得不这样做:return sequelize.define([...]); instead of var Product = sequelize.define([...]); 而不是var Product = sequelize.define([...]); I don't know why but it works now. 我不知道为什么,但它现在有效。 However, I can no longer do a BelongsToMany association directly into the model, and it's quite bad. 但是,我不能再将BelongsToMany关联直接放入模型中,而且非常糟糕。

In 'index.js' file you write:在“index.js”文件中你写:

res.render ('products', {title: 'my title'});

where the list_product is undefined, so when the 'pug file' tries to read this array, it gets a zero length and thus throws the error.其中 list_product 未定义,因此当“哈巴狗文件”尝试读取此数组时,它的长度为零,因此会抛出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM