Erik Erik - 3 months ago 9x
Javascript Question

How to exclude some fields from the document

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:'/example.json', function (req, res) {
var user = new User({name: 'John', age: 45, _creator: 'some ObjectId'}); (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


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.