Home > Software engineering >  trying get the fields names from a mongodb Document
trying get the fields names from a mongodb Document

Time:11-12

so im trying to display the fields name into a html page i used this code to display it but sometimes the result becomes undefined not sure why this is happening the columnNames will return to the html page.

var dataset = mongoose.connection.db.collection(dsName)
  populations = await mongoose.connection.db.collection(dsName  '_pops').distinct("_id", {});

  var mykeys;
  console.log('select');

  dataset.findOne({}, function(err,result) {
  try{
  mykeys = Object.keys(result); //here is the error
  console.log(dataset);
  columnNames = mykeys.splice(0,mykeys.length)
  }catch{
    console.log(dataset);
  }
  if(err){console.log("not working")}

CodePudding user response:

I dont know why when you get a mongodb result you cant convert it with the Object.keys() but i have a trick to share to make it work.

  let contadoresHabiles = await Modelname.find({})


 let dataSting =  JSON.stringify(contadoresHabiles[0])
 let dataSting2 =  JSON.parse(dataSting)
 console.log(dataSting2)
  let mykeys = await Object.keys(dataSting2); //fix the error
  console.log(mykeys)

other important thing its you cant use findOne({}, function(err,result) {}) need an object parameter to find.... instead use find.({}) it will return all objects of that model

CodePudding user response:

The document returned by .findOne() is not a plain JS object. Two options:

1. Convert doc to a plain object:

const doc = await DsName.findOne({});
let myKeys = Object.keys(doc.toObject());
console.log(mykeys);

2. Request a plain object with .lean():

DsName.findOne().lean().exec(function(err, doc) {
  let myKeys = Object.keys(doc.toObject());
  console.log(mykeys);
});
  • Related