Last active
June 6, 2021 08:47
-
-
Save exprodrigues/ee73ca2feb9099a3953626b561b5fb84 to your computer and use it in GitHub Desktop.
Mongoose transform toObject()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: '[email protected]', | |
old: 31 | |
}); | |
console.log(doc.toObject()); | |
console.log(doc.toObject({ hide: '_id old' })); | |
console.log(doc.toObject({ hide: '_id old', transform: true })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! Thank you