Search code examples
node.jspassport.jsknex.js

Find data node js using knex


i just created a function to enter using google oauth. If the data has the same google user id, the data should not add with the same google user id, but what I created can't compare the same data.

Here's my function:

// Check user
    const existingUser = new User(database)
    await existingUser.getUserGoogleId({ google_user_id: profile.id })
    if (existingUser) {
        // eslint-disable-next-line no-console
        console.log('User already exists in our DB')
        // eslint-disable-next-line no-console
        console.log(existingUser)
        return done(null, existingUser)
    }

And here's my repository:

async getUserGoogleId(google_user_id) {
    const query = this.db
        .select(
            'id',
            'google_user_id',
            'username',
        )
        .from(TABLE_NAME)
        .where({
            google_user_id,
        })

    return query.first()
}

Can you guys tell me and maybe give some improvement from it? Thank's. sorry if I have a bad explanation


Solution

  • You are passing an object to your getUserGoogleId, then in the where clause you are creating a nested object.

    The object that you pass to the where clause looks like:

    {
      google_user_id: {
        google_user_id: 'some-id';
      }
    }
    

    All you need to fix this is pass the object it self:

    async getUserGoogleId(google_user_id) {
      return this.db
        .select('id', 'google_user_id', 'username')
        .from(TABLE_NAME)
        .where(google_user_id)
        // --------^
        .first();
    }
    

    Tip: enable .debug() at the end of the query to check what query & params are passed to the DB.