【问题标题】:TypeError: Cannot read property 'findAll' of undefined - Node.js + PostgresqlTypeError:无法读取未定义的属性“findAll”-Node.js + Postgresql
【发布时间】:2021-07-17 14:35:17
【问题描述】:

当我尝试从数据库中获取数据时遇到这个问题

TypeError: 无法读取未定义的属性“findAll”

我使用 react 和 node.js + postgresql 制作了网络。 Postgres 在我们的服务器中,所以我没有使用本地主机。我尝试了其他一些帖子,但一切正常。

服务器.js

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");

const app = express();

var corsOptions = {
  origin: "http://localhost:3000",
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(bodyParser.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
require("./routes/noticias.routes")(app);

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

controller.js

const db = require("../config/db.config");
const noticias = db.noticias;

// Retrieve all noticias from the database.
const getNews = (req, res) => {
  noticias
    .findAll({})
    .then((data) => {
      res.send(data);
    })
    .catch((err) => {
      res.status(500).send({
        message: err.message || "Some error occurred.",
      });
    });
};

module.exports = {
  getNews,
};

路由器

module.exports = (app) => {
  const noticias = require("../controllers/noticias.controller.js");

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

  router.get("/", noticias.getNews);

  app.use("/noticias", router);
};


感谢您的帮助^^

【问题讨论】:

  • const noticias = datab.noticias; 之前添加console.log(datab);。你看到了什么?
  • datab.noticias 未定义

标签: javascript node.js postgresql


【解决方案1】:

使用 db.select('*').from('users') 查找全部

【讨论】:

    【解决方案2】:

    我对 knex 了解不多。据我从文档中了解到,knex 中有一个 select 函数而不是 findAll

    文档:https://knexjs.org/#Builder-select

    请尝试以下方法,看看会发生什么

    
    
    // below line is not required;
    // const noticias = datab.noticias;
    
    // Retrieve all noticias from the database.
    const getNews = (req, res) => {
      datab
        .select("column_name_1", "column_name_2", "...")
        .from("noticias")
        .then((data) => {
          res.send(data);
        })
        .catch((err) => {
          res.status(500).send({
            message: err.message || "Some error occurred.",
          });
        });
    };
    
    

    PS:findAll 函数在 sequelize 而不是 knex 中可用。

    【讨论】:

      猜你喜欢
      • 2016-09-07
      • 2016-04-20
      • 2020-01-23
      • 2020-11-25
      • 2019-10-20
      • 2020-05-15
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多