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
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.
The _id field is included automatically unless specifically excluded.
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.
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.
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.
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; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With