Last active
February 15, 2022 22:59
-
-
Save styopdev/95f3fed98ce3ebaedf5c to your computer and use it in GitHub Desktop.
Get mongoose schema fields, excluding specified values, for lodash.
This file contains hidden or 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
_.mixin({ pickSchema: function (model, excluded) { | |
var fields = []; | |
model.schema.eachPath(function (path) { | |
_.isArray(excluded) ? excluded.indexOf(path) < 0 ? fields.push(path) : false : path === excluded ? false : fields.push(path); | |
}); | |
return fields; | |
} | |
}); | |
// Example | |
var UserSchema = new Schema({ | |
fName: String, | |
lName: String, | |
comments: [{ body: String, date: Date }], | |
date: { type: Date, default: Date.now }, | |
hidden: Boolean, | |
meta: { | |
votes: Number, | |
favs: Number | |
}, | |
createdAt: { type: Date, required: true, default: Date.now } | |
}); | |
var User = mongoose.model('User', UserSchema); | |
_.pickSchema(User); // all schema fields | |
_.pickSchema(User, '_id'); // all except _id | |
_.pickSchema(User, ['_id', 'meta.votes', 'hidden']); // result ['fName', 'lName', 'comments', 'date', 'meta.favs', 'createdAt'] | |
// usage example: filter req.body data, and get only neccessary fields | |
_.pick(req.body, _.pickSchema(User, ['_id', 'createdAt', 'hidden'])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment