Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 617
Erik Avatar asked Jun 22 '12 17:06

Erik


People also ask

How do I exclude fields in MongoDB?

To exclude the _id field from the output documents of the $project stage, specify the exclusion of the _id field by setting it to 0 in the projection document.

Which field is always included in a projection unless specifically excluded?

The _id field is included automatically unless specifically excluded.

Which field is always included in a projection?

Single Field Despite the fact that this projection only explicitly included the name field, the query returned the _id field as well! This happens because the _id field is a special case: it is always included in every query unless explicitly specified otherwise.

What is lean Mongoose?

The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents.


2 Answers

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.

like image 108
Charles Avatar answered Sep 24 '22 10:09

Charles


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;     } }); 
like image 36
Xerri Avatar answered Sep 22 '22 10:09

Xerri