getting schema attributes from Mongoose Model

2019-01-08 18:42发布

问题:

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

回答1:

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.



回答2:

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);


回答3:

Solution for lodash, function which picked all schema properties, excluding specified

_.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;
   }
});

_.pickSchema(User, '_id'); // will return all fields except _id

_.pick(req.body, _.pickSchema(User, ['_id', 'createdAt', 'hidden'])) // all except specified properties

read more here https://gist.github.com/styopdev/95f3fed98ce3ebaedf5c



回答4:

If you want to have only the attributes you added and not the add methods by the ORM that starts with '$___', you have to turn the document into object then access the attributes like this:

Object.keys(document.toObject());


回答5:

In case you want to have all property values (including nested and populated properties), just use toObject() method:

let modelAttributes = null;
SomeModel.findById('someId').populate('child.name').exec().then((result) => {
  modelAttributes = result.toObject();
  console.log(modelAttributes);
});

The output would be:

{
  id: 'someId',
  name: 'someName',
  child: {
    name: 'someChildName'
  }
  ...
}