findAll() 返回 [object SequelizeInstance:table name] (mysql)

问题描述

我的代码是:

app.get('/main',function(req,res) {
  Posts.findAll().then(function(posts){
    res.render(__dirname + "/home.pug",{posts:posts});
  })

在节点和:

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