starsneverfall
starsneverfall

Reputation: 157

Fail to get the specific dataValue from the return sequelize JSON object

I have two data models, one is Passport and the other one is Recipe, now I am working on one of the attributes in Recipe, which is called authorFbPage, and i am trying to get the specific dataValue from Passport, the code is

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);
        }
      },
    }, 

In the beginning, the User would be a huge sequelize return, so I tried to make it a JSON object, then I use JSON.parse to transfer it into below object

{ 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 }

and when I try to console the provider from this object, it returns "undefined", it really confused me since I already transfer it to an object, why it still won't get the value?

Upvotes: 0

Views: 2798

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58543

Instead of using these much code : (Please read comment also)

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

Solution :

First change findAll to findOne as per the code I think you only need User object not array of object.

Just use raw : true , it will return json object with values only , no other extra stuff :

const User = await models.Passport.findOne({ raw : true , where: { UserId: thisUser } });

OR use .toJSON()

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

Upvotes: 2

Related Questions