Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove one property from mongoose 'toJSON' support

I am using mongoose's toJSON support as below:

userSchema.set('toJSON', { getters: true, virtuals: true, minimize: false })

now in the returned result from a mongoose object's toJSON() method call, I want to remove certain sensitive fields. How to do that?

In different way to explain the issue:

Some certain fields like 'password', 'token' which we would need only in query, but not in returned result, how to hide them from returning from all kind of queries?

Update: This finally what I ended up with and working like a charm:

userSchema.options.toJSON = {
    getters: true,
    virtuals: true,
    minimize: false,
    transform: function (doc, ret, options) {
      delete ret.password
      delete ret.authToken
      return ret
    }
  }
like image 538
Rana Avatar asked Sep 04 '15 05:09

Rana


1 Answers

you can customize how toJSON works on your schema like this:

/**
  * adjust toJSON transformation
  */ 
mySchema.options.toJSON = {
    transform: function(doc, ret, options) {
        ret.id = ret._id;
        delete ret.password;
        delete ret.token;
        delete ret._id;
        delete ret.__v;
        return ret;
    }
};

doc is the document to be serialized, ret is the plain JS object that will be transformed into JSON. You may then manipulate ret however you want.

like image 87
Reto Avatar answered Nov 09 '22 07:11

Reto