node.js - ejs如何从对象中提取值

标签 node.js sequelize.js ejs

我正在使用 Sequelize,我使用 从表中获取所有数据查找全部 .这基本上是一个对象数组。似乎令人困惑的是,我作为输出显示的数据嵌套在对象下。 (听起来令人困惑?让我澄清一下)

所以,让我有这个短代码

enter image description here

在这里,如果我运行这段代码,它会给我 undefine 因为 父亲 在于 parent ,为此我必须使用 user.parent.father , 对?

好的,现在在我的代码中从表中获取数据,
enter image description here

我 console.log 我的第一行,为此我得到了这个。
enter image description here

现在,我需要的值位于 dataValues 中。

在我的 ejs 文件中。我正在使用简单的 for-of 循​​环

enter image description here

现在我的问题是为什么我没有为 product.title , product.imageUrl 等等得到 undefined ?它应该通过 product.dataValues.title 获取这些数据。因为它位于另一个对象名称 dataValues 中。

最佳答案

从技术上讲,当一个值被 Sequelize 初始化时,你的对象的原型(prototype)被设置为 Model (类(class)太长,无法在此处复制粘贴)。
创建模型时,Sequelize 会调用 init在它上面(第 424 行),然后调用 refreshAttributes .
这个叫Object.defineProperty为您在元数据中定义的每个属性定义 getter 和 setter(第 1238 行)。
getter 和 setter 设置为 getset功能(第 1095 到 1103 行)。
这实际上意味着

instance.field
只是一个被包裹的属性
instance.get('field')
这对应于 their docs它说

Instance instances operate with the concept of a dataValues property, which stores the actual values represented by the instance. By default, the values from dataValues can also be accessed directly from the Instance, that is:

instance.field

is the same as

instance.get('field')

is the same as

instance.getDataValue('field')

关于node.js - ejs如何从对象中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57201507/

相关文章:

node.js - 无论如何使用 Node js 发送 WhatsApp 消息?

reactjs - 如何在 Reactjs 中使用 sequelize 添加或条件

javascript - 允许 sequelize 外键的空值?

mysql - Sequelize 使用 MySQL 抛出断言错误

javascript - 在下拉菜单中设置选定值

javascript - 即使正确渲染,EJS 变量也会引发错误

javascript - Bootstrap 崩溃动态 'data-target' 未按预期工作

node.js - 为什么远程服务器响应在获取请求后不包含 nodejs 上的 x-csrf-token?

node.js - Grunt-mocha-test Xunit 报告器将整个控制台输出写入 xunit 文件

javascript - 获取 Telegram 群的所有用户