getting schema attributes from Mongoose Model

53,130

Solution 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.

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

Solution 3

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

Solution 4

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

Solution 5

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());
Share:
53,130
user1460015
Author by

user1460015

Updated on July 08, 2022

Comments

  • user1460015
    user1460015 almost 2 years

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

  • user1460015
    user1460015 about 11 years
    could you provide a resource?
  • gustavohenke
    gustavohenke about 11 years
    I dont't understand. Do you want links?
  • user1460015
    user1460015 almost 11 years
    sure... just something that I can reference in the future instead of asking questions here.
  • sinθ
    sinθ over 10 years
    Is there a way to get this from a database object if you don't know the schema?
  • gustavohenke
    gustavohenke over 10 years
    Maybe try iterating thru the registered models with modelNames(), then you retrieve the models and their paths the same way.
  • Saksham Khurana
    Saksham Khurana about 6 years
    To add in to the answer , if you have created a Schema named Temp then you can access the object using Temp.paths
  • Predrag Stojadinović
    Predrag Stojadinović almost 3 years
    The tree attribute is better than paths because it includes virtuals.