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")}
2
Answers
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.
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
The document returned by
.findOne()
is not a plain JS object. Two options:1. Convert doc to a plain object:
2. Request a plain object with
.lean()
: