Home > OS >  From MongoDB Schema, how to extract its keys
From MongoDB Schema, how to extract its keys

Time:07-05

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

CodePudding user response:

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