node.js - 无法从返回的 sequelize JSON 对象中获取特定的 dataValue

标签 node.js sequelize.js

我有两个数据模型,一个是 Passport,另一个是 Recipe,现在我正在研究 Recipe 中的一个属性,称为 authorFbPage,我正在尝试从 Passport 获取特定的 dataValue,
代码是

authorFbPage: {
      type: DataTypes.VIRTUAL,
      async get() {
        try {
          const thisUser = await this.getDataValue('UserId');
          let fbId = 'https://www.facebook.com/LabFnP';
          const User = await models.Passport.findAll({ where: { UserId: thisUser } });
          const Passport = await JSON.stringify(User);
          const PassportValue = await JSON.parse(Passport);
          console.log(PassportValue.provider);
          //The problem happened in here!
          return fbId;
        } catch (e) {
          console.log(e);
        }
      },
    }, 

一开始, User 会是一个巨大的 sequelize 返回,所以我试图把它变成一个 JSON 对象,然后我使用 JSON.parse 将它转换成下面的对象
{ id: 2,
[0]   protocol: 'oauth2',
[0]   accessToken: null,
[0]   provider: 'google',
[0]   authority: null,
[0]   identifier: '109412096578527604841',
[0]   tokens: 'token',
[0]   salt: null,
[0]   createdAt: '2018-03-08T09:46:13.000Z',
[0]   updatedAt: '2018-03-08T09:46:13.000Z',
[0]   UserId: 61 }

当我尝试从这个对象控制台提供程序时,它返回“未定义”,这真的让我感到困惑,因为我已经将它转移到了一个对象,为什么它仍然无法获得该值?

最佳答案

而不是使用这些代码:(请阅读评论)

const User = await models.Passport.findAll({ where: { UserId: thisUser } });
const Passport = await JSON.stringify(User); // remove await this is not async process
const PassportValue = await JSON.parse(Passport); // remove await this is not async process

解决方案:

首先根据代码将 findAll 更改为 findOne 我认为您只需要 User 对象而不是对象数组。

只需使用 raw : true ,它只会返回带有值的 json 对象,没有其他额外的东西:
const User = await models.Passport.findOne({ raw : true , where: { UserId: thisUser } });

或使用 .toJSON()
const User = await models.Passport.findOne({ where: { UserId: thisUser } });
const PassportValue = User.toJSON();

关于node.js - 无法从返回的 sequelize JSON 对象中获取特定的 dataValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49552040/

相关文章:

node.js - 如何避免 nodejs 中的回调 hell 以进行 Sequelize

mysql - Sequelize 可以处理与一个表关联的多个键吗?

javascript - Sequelize js 如何使用 OR 运算符创建多个类似条件

javascript - 使用 Node.js 和 MongoDB 存储密码

Node.js 通过查询字符串传递参数

javascript - 快速 GET 路线不起作用

node.js - npm 不工作 - "read ECONNRESET"

Node.js Sequelize 连接

node.js - Sequelize 和羽毛 : When Relationships Fall Apart

node.js - 是否可以将文件发布到 MQTT 服务器?