Skip to content

Instantly share code, notes, and snippets.

@styopdev
Last active Apr 24, 2020
Embed
What would you like to do?
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