我正在使用 Sequelize,我使用 从表中获取所有数据查找全部 .这基本上是一个对象数组。似乎令人困惑的是,我作为输出显示的数据嵌套在对象下。 (听起来令人困惑?让我澄清一下)
所以,让我有这个短代码
在这里,如果我运行这段代码,它会给我 undefine 因为 父亲 在于 parent ,为此我必须使用 user.parent.father , 对?
好的,现在在我的代码中从表中获取数据,
我 console.log 我的第一行,为此我得到了这个。
现在,我需要的值位于 dataValues 中。
在我的 ejs 文件中。我正在使用简单的 for-of 循环
现在我的问题是为什么我没有为 product.title , product.imageUrl 等等得到 undefined ?它应该通过 product.dataValues.title 获取这些数据。因为它位于另一个对象名称 dataValues 中。
最佳答案
从技术上讲,当一个值被 Sequelize 初始化时,你的对象的原型(prototype)被设置为 Model
(类(class)太长,无法在此处复制粘贴)。
创建模型时,Sequelize 会调用 init
在它上面(第 424 行),然后调用 refreshAttributes
.
这个叫Object.defineProperty
为您在元数据中定义的每个属性定义 getter 和 setter(第 1238 行)。
getter 和 setter 设置为 get
和 set
功能(第 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/