I'm using Mongoose.js to create models with schemas.
I have a list of models (many) and at times I'd like to get the attributes/keys that make up a particular model.
Is there a method to pull out the attribute schemas for any given model?
For example,
var mySchema = module.exports = new Schema({ SID: { type: Schema.Types.ObjectId //, required: true }, teams: { type: [String] }, hats: [{ val: String, dt: Date }], shields: [{ val: String, dt: Date }], shoes: [{ val: String, dt: Date }] }
);
Is it possible to pull out/identify the attributes of the schema [SID, hats, teams, shields, shoes]
??
Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
In Mongoose, a schema is a configuration object for a model. Schemas do not allow you to read and write from MongoDB, that's what models are for. But they do: Define what properties the documents you save in MongoDB can have. Define custom validation.
mongoose. model() returns a Model ( It is a constructor, compiled from Schema definitions).
The $set operator replaces the value of a field with the specified value.
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With