21

I know with options.attributes you list the attributes that you want to select but Is there a way to only exclude a field ?

By now I worked it out with

User
  .findAll({order: [['id','DESC']]})
  .then(function(users) {
    users = users.filter(function(user){
      delete user.dataValues.password;
      return user;
    });
    return reply( ReplyUtil.ok(users) );
  })
  .catch(function(err){
    return reply( ReplyUtil.badImplementation(err) );
  });

BTW

I don't understand why on earth you should use user.dataValues.password if not delete doesn't work instead of simply user.password if I debug like this console.log('pass: ', user.password)I can see the password.

4 Answers 4

40

Yes it's possible to exclude fields, just like this :

User
  .findAll({
    attributes: {exclude: ['password']},
    order: [['id','DESC']]})
  .then( users => {
    return reply( ReplyUtil.ok(users) );
  })
  .catch( err => {
    return reply( ReplyUtil.badImplementation(err) );
  });

For more details see https://sequelize.org/master/manual/querying.html

7

If you have access to the model definition, one approach (available in v6 Sequelize as of this writing), is utilizing the defaultScope. This provides a means to define how the all responses will be returned (by default), avoiding the need to repeat the filter in each usage. For example:

User.init(
  {...},  // Model fields
  {       // Options
    sequelize, 
    modelName: 'User',
    defaultScope: {
      attributes: {
        exclude: ['password']
      },
      order: [['id', 'DESC']]
    },
    scopes: {
      withPassword: {
        attributes: {
          include: ['password']
        }
      }
    }
  }
)

In the example, a defaultScope is defined excluding the password field and a custom scope to include the password field again is provided, for instances where it's explicitly needed. These can be called as:

// Has no password field in results:
User.findAll();

// Has password field in results:
User.scope('withPassword').findAll();

Scopes are useful, but the defaultScope is unique as the only one that modifies the base query results. There are several other options available within scopes as well to further customize result structures.

NOTE: When specifying a .scope(...) manually, it will remove the defaultScope, use .scope(['defaultScope', ...]) to ensure it's included. For example:

User.scope(['defaultScope','active','withEmployer']).findAll();
2

I know this is an old post. But I came here because of this same problem and I believe that more people will come. So, after studying some posts here in stackoverflow, I discovered that the simplest way is to use the select function to specify the fields we do not want to return. So its function would look like this:

User
  .findAll({order: [['id','DESC']]}).select('-password')
  .then(function(users) {
    return reply( ReplyUtil.ok(users) );
  })
  .catch(function(err){
    return reply( ReplyUtil.badImplementation(err) );
  });

Another way is to change the model (by code, I'm assuming you specified this model with mongoose or sequelize). You can specify the field like this:password: { type: String, select: false }. This select will cause the password, by default, not to be returned by any query in the database. Unless you use the previous function to add the password in the query (select ('+ password')).

AND

To answer your main question, Mongoose and Sequelize wraps all it's return values in a virtual object that contains meta data. If you have an object and you just want the undecorated you have to unwrap them, like that:

Model.findById(1).then(data => {
  console.log(data.get({ plain: true }));
});

And if you just want to print the object you can use the .toJSON:

Model.findById(1).then(data => {
  console.log(data.toJSON);
});

And if you just want the data and not the model instance, you can do this:

Model.findAll({
  raw: true
});
1
  • Model.findAll().select is not a function. Using Sequelize v6.12.5 Apr 29, 2022 at 13:41
1

I use the SandWyrm pattern, but i suppose that he made a mistake, I use this code to exclude password:

User.init(
  {...},  // Model fields
  {       // Options
    sequelize, 
    modelName: 'User',
    defaultScope: {
      attributes: {
        exclude: ['password']
      },
      order: [['id', 'DESC']]
    },
    scopes: {
      withPassword: {
        attributes: {}
      }
    }
  }
)

Cause with include field in withPassword scope it add password two times on query and we retrieve an error, I hope it helps. Of course after that you can use

// Has password field in results:
User.scope('withPassword').findAll()

Scope references

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.