javascript - 如何在 sequelize 中编写查询以查找与 user_id 关联的所有待办事项

标签 javascript node.js sqlite express sequelize.js

我正在使用 node express ejs 编写第一个待办事项列表应用程序并使用 sqlite 进行 Sequelize

我的数据库模式的 sqlite.js 文件如下

const Sequelize = require("sequelize");
const sequelize = new Sequelize({
  dialect: "sqlite",
  storage: "./src/backend/databases/database.sqlite",
});

const users = sequelize.define("user", {
   username: {
    type: Sequelize.STRING,
  },
  email: {
    type: Sequelize.STRING,
    unique: true,
    allowNull: false,
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false,
  },
});

const lists = sequelize.define("list", {
  item: {
    type: Sequelize.STRING,
  },
  edit: {
    type: Sequelize.BOOLEAN,
  },
  done: {
    type: Sequelize.STRING,
  },
  user_id: {
    type: Sequelize.NUMBER,
  },
});


sequelize
  .sync()
  .then(() => {
    console.log("tables have been successfully created");
    //  return sequelize.drop();
  })
  .catch((e) => console.log(e));

module.exports = {
  users: users,
  lists: lists,
};


我想访问和显示与 user_id 相关的所有待办事项。我使用了 sequelize findall 方法如下
const dbConn = require("../databases/sqlite.js");
const list = dbConn.list;

 list.findAll({ where: { user_id: user_id } }).then((todoList) => {
    res
      .render("profile", { todoList: todoList })
      .catch((err) => console.error(err));
  });


但我无法在 ejs 文件中显示。它说待办事项列表未定义

.ejs 文件
 <div class="addedTask">
            <h3>Added tasks</h3>
              <% for( let i = 0; i< todoList.length ; i++){ %>
                <% console.log(todoList[i])%>
              <% } %>
          </div>

显示的错误是——
[ todoList 未定义 ]

如何更改我的方法以显示与单个 user_id 关联的所有待办事项

提前致谢

最佳答案

list.findAll({ where: { user_id: user_id } }).then((todoLists) => {
    res
      .render("profile", { todoLists });
  }).catch((err) => console.error(err));

你能告诉我你从哪里得到 user_id 吗?

关于javascript - 如何在 sequelize 中编写查询以查找与 user_id 关联的所有待办事项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61654652/

相关文章:

javascript - 我如何测试元素是否在 JavaScript 中自封闭?

javascript - 这个简单的 Safari 扩展代码有什么问题?

javascript - Angular.js 两个嵌套 Controller 之间的双向数据绑定(bind)

node.js - Nodemon运行明确错误

javascript - 将 asar 包中的打包 JS 文件传递​​给生成的 Node 子进程

javascript - IE 是否为每个脚本标签创建新的范围?

node.js - 找出所有正在运行的node.js应用程序的pid和端口

c++ - 来自数据库的 QT ComboBox ItemData

sqlite - 如何根据表中值的存在创建SQLite触发器?

C#:SQLite 数据库始终处于锁定状态