简体   繁体   中英

Bookshelf.js - How to get 'hidden' fields for one query only?

I have the following Bookshelf model :

Bookshelf.model.extend({
  tableName: 'users',
  hidden: ['password']
}, { 
  async getBy(filter) {
    return await this.query({where: filter}).fetch();
  }
})

As you see, the field password is hidden (because I usually don't want it to be shown).
But, I need it to connect my user (when doing the hash comparison) :

const user = await userModel.getBy({email: req.body.email});
if (await bcrypt.compare(req.body.password, user.password)) { 
  // here user.password is undefined because it is hidden
}

Is there a way to shortcut the visibility plugin and get the password without having to do things like directly using knex ( Bookshelf.knex.raw() ) ?

Best regards,

OK, since I've found a solution, I'll answer my own question and I hope it will help some people :

14 days ago (30/06/2017), the issue #1379 has been merged.

It provides the following functionnality :

Adds ability to override options specified during forging with the options specified to toJSON directly.

Here is the commit, the tests show how it works.

For my case, I do the following :

const user = (await userModel.getBy({email: req.body.email})).toJSON({hidden: []});

hidden is an empty array, so it overrides the previous hidden property ( hidden: ['password'] ) and get the passwords to be shown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM