70

I have the following simple shema:

 var userSchema = new Schema({
    name : String,
   age: Number,
   _creator: Schema.ObjectId
  });

  var User = mongoose.model('User',userSchema);

What I want to do is create the new document and return to client, but I want to exclude the 'creator' field from one:

app.post('/example.json', function (req, res) {
   var user = new User({name: 'John', age: 45, _creator: 'some ObjectId'});
   user.save(function (err) {
      if (err) throw err;

      res.json(200, {user: user});     // how to exclude the _creator field?
   });
});

At the end I want to send the new created user without _creator field:

{
   name: 'John',
   age: 45
} 

Is it possible to make without extra find request to mongoose?

P.S:It's preferable to make it by

2
  • 1
    create a new json object without said field and return it. What's the problem? Commented Jun 22, 2012 at 17:10
  • @SergioTulentsev Too verbose! There should be some better way.
    – awvalenti
    Commented Apr 20, 2018 at 17:32

8 Answers 8

84

Another way to handle this on the schema level is to override toJSON for the model.

UserSchema.methods.toJSON = function() {
  var obj = this.toObject()
  delete obj.passwordHash
  return obj
}

I came across this question looking for a way to exclude password hash from the json i served to the client, and select: false broke my verifyPassword function because it didn't retrieve the value from the database at all.

5
  • 8
    Try using UserSchema.set('toJSON', { transform: function(doc, ret, options) { delete ret.password; return ret; } });
    – Xerri
    Commented Jun 12, 2013 at 10:48
  • Just a beware to anyone copying this code, obj should have a var statement before it, or it will leak a global reference.
    – Jed Watson
    Commented Jan 21, 2014 at 6:39
  • 1
    @SirBenBenji You are missing the point. The point is adding a toJSON method wherein you can transform the output. The passwordHash property is, itself, irrelevant
    – Mike Caron
    Commented Oct 17, 2014 at 13:12
  • nice solution instead of create new object and dont set all fields except passwordHash
    – ofir_aghai
    Commented Jul 7, 2016 at 8:58
  • Is there a way to expand this to conditionally filter fields? For example, admin wants to see an "approved_by" but normal client should not.
    – bgura
    Commented Feb 14, 2020 at 23:54
63

The documented way is

UserSchema.set('toJSON', {
    transform: function(doc, ret, options) {
        delete ret.password;
        return ret;
    }
});

UPDATE - You might want to use a white list:

UserSchema.set('toJSON', {
    transform: function(doc, ret, options) {
        var retJson = {
            email: ret.email,
            registered: ret.registered,
            modified: ret.modified
        };
        return retJson;
    }
});
5
  • 7
    or, if your have already underscore/lodash, you can use _.pick UserSchema.set('toJSON', { transform: function(doc, ret, options) { return _.pick(ret, 'email', 'registered', 'modified') } }) Commented Mar 21, 2014 at 0:41
  • @xerri - where is this documented? i see toJSON, but having trouble finding transform Commented Nov 4, 2014 at 22:52
  • @xerri - found it, just got confused, since the docs are under toObject not toJSON ==> mongoosejs.com/docs/api.html#document_Document-toObject Commented Nov 4, 2014 at 23:07
  • 1
    This is not working in mongoose v4.4.6^ when updating with findByIdAndUpdate. Any help please?
    – Goran
    Commented Aug 19, 2016 at 11:12
  • Not working in v6.0.12 with findByIdAndUpdate or save methods. Tried code here and also from docs for both toObject and toJson. No errors but password field still gets sent to client for post and update. For now I'm handling it in my router with a custom object and res.json() till I can figure out why it isn't working in my schema
    – isimmons
    Commented Nov 9, 2021 at 23:19
18

Come across your question when I was trying to find a similar answer with pymongo. It turns out that in mongo shell, with the find() function call, you can pass a second parameter which specifies how the result document looks like. When you pass a dictionary with attribute's value being 0, you are excluding this field in all the document that come out of this query.

In your case, for example, the query will be like:

db.user.find({an_attr: a_value}, {_creator: 0});

It will exclude _creator parameter for you.

In pymongo, the find() function is pretty much the same. Not sure how it translate to mongoose though. I think it's a better solution compare to manually delete the fields afterwards.

Hope it helps.

4
  • Although the others might work, this seems like the correct answer to me. Worked for me.
    – abritez
    Commented May 21, 2013 at 4:14
  • This may work in some cases, but not most, because even if you don't want to display the field there's a good chance you want it to operate on in the backend. The problem with this solution and many others like it is that the field in question is never retrieved from the database. If you have other calculated or virtual fields that depend on it, they will not be set properly.
    – jfmatt
    Commented Jun 14, 2013 at 18:16
  • 2
    Bypassing Mongoose seems to be the Recommended Way of doing things in Mongoose these days. Let's one wonder if Mongoose is up to the task at all..
    – Stephan K.
    Commented Sep 18, 2014 at 9:19
  • @nottinhill Extraneous apostrophe!
    – binki
    Commented Jul 19, 2017 at 1:38
15

I would use the lodash utilities .pick() or .omit()

var _ = require('lodash');

app.post('/example.json', function (req, res) {
    var user = new User({name: 'John', age: 45, _creator: 'some ObjectId'});
    user.save(function (err) {
        if (err) throw err;
        // Only get name and age properties
        var userFiltered = _.pick(user.toObject(), ['name', 'age']);
        res.json(200, {user: user});
    });
});

The other example would be:

var _ = require('lodash');

app.post('/example.json', function (req, res) {
    var user = new User({name: 'John', age: 45, _creator: 'some ObjectId'});
    user.save(function (err) {
        if (err) throw err;
        // Remove _creator property
        var userFiltered = _.omit(user.toObject(), ['_creator']);
        res.json(200, {user: user});
    });
});
15

You can call toObject() on the document to convert it to a plain JS object that you can freely modify:

user = user.toObject();
delete user._creator;
res.json(200, {user: user});
3
  • Thank you for answer, can I define a fields that never return on a Schema level?
    – Erik
    Commented Jun 22, 2012 at 19:23
  • 4
    You can hide schema fields by default by including select: false in the field's definition.
    – JohnnyHK
    Commented Jun 22, 2012 at 19:46
  • This is a much better way to do it than changing the default serialization for all objects. Commented Oct 10, 2016 at 15:54
11

By following the MongoDB documentation, you can exclude fields by passing a second parameter to your query like:

User.find({_id: req.user.id}, {password: 0})
        .then(users => {
          res.status(STATUS_OK).json(users);
        })
        .catch(error => res.status(STATUS_NOT_FOUND).json({error: error}));

In this case, password will be excluded from the query.

font: https://docs.mongodb.com/v2.8/tutorial/project-fields-from-query-results/#return-all-but-the-excluded-field

2
  • This is a clear and simple solution Commented Feb 24, 2022 at 20:47
  • Lovely! Pretty nice
    – Norak
    Commented Nov 27, 2023 at 6:42
1

I am using Mongoosemask and am very happy with it.

It does support hiding and exposing properties with other names based on your need

https://github.com/mccormicka/mongoosemask

var maskedModel = mongomask.mask(model, ['name', 'age']); //And you are done.

0

You can do this on the schema file itself.

// user.js
var userSchema = new Schema({
    name : String,
    age: Number,
   _creator: Schema.ObjectId
  });

userSchema.statics.toClientObject = function (user) {
  const userObject = user?.toObject();
  // Include fields that you want to send
  const clientObject = {
    name: userObject.name,
    age: userObject.age,
  };

  return clientObject;
};

var User = mongoose.model('User',userSchema);

Now, in the controller method where you are responding back to the client, do the following

return res.json({
    user: User.toClientObject(YOUR_ENTIRE_USER_DOC),
  });

Your Answer

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

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