object SequelizeInstance being pass

穿精又带淫゛_ 提交于 2021-01-21 11:22:22

问题


I am confused and I hope you can help me. I am building an app in node.js using express.js and sequelize for my ORM. I have created a model with the following code:

"use strict";

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: DataTypes.STRING
  });

  return User;
};

My route looks like this:

router.get('/', function (req, res) {
  models.User.findAll({ }).then(function(users) {
    res.render('index', {
      title: 'Project Insight',
      users: users
    });
  });
})

And I am using EJS for my templates:

<ul>
    <% for(var i=0; i<users.length; i++) {%>
      <li><%= users[i] %></li>
    <% } %>
</ul>

The output I getting in my views is this:

[object SequelizeInstance]
[object SequelizeInstance]
[object SequelizeInstance]
[object SequelizeInstance]

I want to be able to pull the names from the database and I am confused about why this is giving that result. Please let me know if there is any info you need from me. I am new to all of this and I am at a standstill. Thanks, in advance, for all your help.


回答1:


Try to change EJS template:

<ul>
    <% for(var i=0; i<users.length; i++) {%>
      <li><%= users[i].username %></li>
    <% } %>
</ul>



回答2:


Might be helpful for other people:

model.findAll({where}).
  .then(res => {
    return res.map(row => {
      return row.dataValues
    });
  })

Which will return list of objects that looks like:

[
  {
    column1: value1,
    column2: value2,
    ...
    columnN: valueN
  }
]


来源:https://stackoverflow.com/questions/28097020/object-sequelizeinstance-being-pass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!