Skip to content

Instantly share code, notes, and snippets.

@exprodrigues
Last active June 6, 2021 08:47
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exprodrigues/ee73ca2feb9099a3953626b561b5fb84 to your computer and use it in GitHub Desktop.
Save exprodrigues/ee73ca2feb9099a3953626b561b5fb84 to your computer and use it in GitHub Desktop.
Mongoose transform toObject()
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const schema = new mongoose.Schema({
_id: String,
name: String,
email: String,
old: Number
});
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.hide = '_id';
schema.options.toObject.transform = function (doc, ret, options) {
if (options.hide) {
options.hide.split(' ').forEach(function (prop) {
delete ret[prop];
});
}
return ret;
}
const User = mongoose.model('User', schema);
const doc = new User({
_id: 'john',
name: 'John Doe',
email: 'john@doe.com',
old: 31
});
console.log(doc.toObject());
console.log(doc.toObject({ hide: '_id old' }));
console.log(doc.toObject({ hide: '_id old', transform: true }));
@santiq
Copy link

santiq commented Aug 16, 2018

Nice! Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment