getting schema attributes from Mongoose Model
My solution uses mongoose model.
Schema attributes
const schema = {
email: {
type: String,
required: 'email is required',
},
password: {
type: String,
required: 'password is required',
},
};
Schema
const FooSchema = new Schema(schema);
Model
const FooModel = model('Foo', FooSchema);
Get attributes from model:
Object.keys(FooModel.schema.tree)
Result:
[
'email',
'password',
'_id',
'__v'
]
Don't have enough rep to comment, but this also spits out a list and loops through all of the schema types.
mySchema.schema.eachPath(function(path) {
console.log(path);
});
should print out:
number
name.first
name.last
ssn
birthday
job.company
job.position
address.city
address.state
address.country
address.street
address.number
address.zip
email
phones
tags
createdBy
createdAt
updatedBy
updatedAt
meta
_id
__v
Or you could get all Attributes as an Array like this:
var props = Object.keys(mySchema.schema.paths);
Yes, it is possible.
Each schema has a paths
property, that looks somewhat like this (this is an example of my code):
paths: {
number: [Object],
'name.first': [Object],
'name.last': [Object],
ssn: [Object],
birthday: [Object],
'job.company': [Object],
'job.position': [Object],
'address.city': [Object],
'address.state': [Object],
'address.country': [Object],
'address.street': [Object],
'address.number': [Object],
'address.zip': [Object],
email: [Object],
phones: [Object],
tags: [Object],
createdBy: [Object],
createdAt: [Object],
updatedBy: [Object],
updatedAt: [Object],
meta: [Object],
_id: [Object],
__v: [Object]
}
You can access this through an model too. It's under Model.schema.paths
.