Skip to content

Instantly share code, notes, and snippets.

@styopdev
Last active February 15, 2022 22:59
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save styopdev/95f3fed98ce3ebaedf5c to your computer and use it in GitHub Desktop.
Save styopdev/95f3fed98ce3ebaedf5c to your computer and use it in GitHub Desktop.
Get mongoose schema fields, excluding specified values, for lodash.
_.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