Search code examples
mongodbmongoose-schema

From MongoDB Schema, how to extract its keys


I have a MongoDB Schema which looks like this -

const BusSchema = mongoose.Schema(
  {
    busNumber: { type: String },
    cityId: { type: String },
    agencyId: { type: String },
    afcsAccountId: { type: String },
    agencyName: { type: String },
    depotName: { type: String },
    afcsAccountName: { type: String },
    operatorEmailId: { type: String },
    operatorMobile: { type: String },
});
const Bus = mongoose.model('Bus', BusSchema);
module.exports = Bus;

I want to access the keys of this schema i.e column names in some other file but I can not export the BusSchema separately. How can I do that without changing the above file? I am trying to use syntax like -

import Bus = require('../bus');
console.log( Object.keys(Bus.Schema()) )

something like this, but not sure how to get the below output.

busNumber
cityId
agencyId
afcsAccountId
depotName
afcsAccountName
operatorEmailId
operatorMobile

Solution

  • Try this:

    const Bus = require('mongoose').model('Bus');
    var myKeys;
    
    const getKeys = async () => {
        await Bus.findOne({}, (err, result) {
            myKeys = Object.keys(result._doc);
        });
    }
    
    getKeys();
    

    Alternatively, may also try this code:

    const keys = Object.keys(Bus.schema.obj);