mysql - findAll() 返回 [对象 SequelizeInstance :table name] (mysql)

标签 mysql node.js express sequelize.js pug

我的代码是:

app.get('/main', function(req, res) {
  Posts.findAll().then(function(posts){
    res.render(__dirname + "/home.pug", {posts:posts});
  })
在 Node 和:
div
  each val in posts
    li= val
在 pug 处,但它返回:[object SequelizeInstance:mensages](mensages 是数据库名称)而不是值
对不起我的英语,如果问题令人困惑

最佳答案

因为您正在尝试渲染 Posts.findAll() 方法返回的 sequelize 的 model instances
您可能想要呈现 post 的属性,而不是整个模型实例对象。
例如。app.ts :

import express from 'express';
import path from 'path';
import { DataTypes, Model } from 'sequelize';
import { sequelize } from '../../db';

class Posts extends Model {}
Posts.init(
  {
    name: DataTypes.STRING,
  },
  { sequelize, tableName: 'posts' },
);

const app = express();

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

app.get('/', (req, res) => {
  Posts.findAll().then(function(posts) {
    res.render('home.pug', { posts: posts });
  });
});

(async function main() {
  await sequelize.sync({ force: true });
  //seed
  await Posts.bulkCreate([{ name: 'teresa' }, { name: 'teng' }]);
  app.listen(3000, () => console.log('Server started at http://localhost:3000'));
})();
views/home.pug :
<!DOCTYPE html>
html(lang="en")
    head
        meta(charset="UTF-8")
        meta(name="viewport", content="width=device-width, initial-scale=1.0")
        title Document
    body
        div
            each val in posts
                li= val.name
HTML 输出:
enter image description here
源代码:https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/65376890

关于mysql - findAll() 返回 [对象 SequelizeInstance :table name] (mysql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65376890/

相关文章:

php - 如何在 PHP 中包含 MYSQL 的前 5 行表

mysql - 按重要性和 id 对 mysql 进行排序

node.js - 未找到 PM2 命令

node.js - 如何在 Express 中重复使用带 Handlebars 的布局?

javascript - 将附加参数传递给路由(expressjs)

Mysql - 从嵌套子查询引用外部字段

php - 如何让 HAproxy 返回下一个数据库服务器的 IP 地址?

javascript - Promise 链中的 for 循环中的 Promise

javascript - Node JS 运行两个不同的数据库

mysql - 使用 Node 和 Express 将表中的多个选定 ID 发送到路由中