Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mongodb - getting schema attributes from Mongoose Model

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]??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...