mongoose 尝试从mongodb文档中获取字段名称

dpiehjr4  于 2022-11-13  发布在  Go
关注(0)|答案(2)|浏览(157)

因此,我试图将字段名称显示到html页面中,我使用了此代码来显示它,但有时结果变得未定义,不确定为什么会发生这种情况,列名称将返回到html页面。

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")}
u0njafvf

u0njafvf1#

我不知道为什么当你得到一个mongodb结果时,你不能用Object.keys()转换它,但是我有一个技巧可以让它工作。

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)

另一件重要事情是,您不能使用findOne({},function(err,result){}),它需要一个对象参数来查找....而应使用find.({}),它将返回模型的所有对象

fhg3lkii

fhg3lkii2#

.findOne()返回的文档不是普通的JS对象。有两个选项:

1.将文档转换为普通对象:

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

2.使用.lean()请求普通对象:

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

相关问题