coinhndp
coinhndp

Reputation: 2471

Remove field from query mongoose

My User model have name,..., password, resetToken, resetTokenExp property.

If I query user (findById, find({}),...), I want to drop password, resetToken and resetTokenExp field

User.findById(id)
  .select('-password -resetToken -resetTokenExp')  
  .exec()

I can use select but these fields are common ones and I dont want to type select everytime I query. How can I set remove these fields globally for User schema

Upvotes: 0

Views: 1208

Answers (2)

Nishant
Nishant

Reputation: 311

In you user Model Schema please refer below code.

You can use Mongoose Transform behavior Link:

Below code will help you to drop password, resetToken and resetTokenExp globally.

And in this code you can also replacing _id with id globally.

UserModel.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: String,
    password: String,
    resetToken: String,
    resetTokenExp: String

}, {
    timestamps: true,
    toObject: {
      transform: function (doc, ret, options) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.password;
        delete ret.resetToken
        delete ret.resetTokenExp
        return ret;
     }
   }
  });

module.exports = mongoose.model('User', userSchema);

Upvotes: 1

Thamaraiselvam
Thamaraiselvam

Reputation: 7080

You can make reusable functions something like this

so by default, these three fields will be excluded from the result

function fetchUser(id, exludeFields = { password: false, resetToken: false, resetTokenExp: false }) {
    return User.findById(id)
        .select(exludeFields)
        .exec();
}

Upvotes: 0

Related Questions