如何从 mongoose mongodb 查询中获取字段的值?

Bal*_* Ks 2 mongoose mongodb node.js

这是我的主 js 文件中的一段代码,我用它来调用另一个 js 文件(js.js)中的函数

  var fields = "workaholic alcoholic insomniac";
  var valid = require("./js");
  Hacker.find({name: "arun"}, fields)//, function(err, hackers) {
      .then(valid.myfun)
      .catch(err => console.log(err,fields));
Run Code Online (Sandbox Code Playgroud)

这是我在主 js 文件中引用的 js.js 文件

exports.myfun = function(hackers) {
    console.log(hackers);
    console.log(hackers.workaholic);
    var workaholic = hackers.workaholic;
    var alcoholic = hackers.alcoholic;
    var insomniac = hackers.insomniac;
    console.log(workaholic);
    console.log(alcoholic);
    console.log(insomniac);
    show(workaholic,alcoholic,insomniac);
}
    function show(a,b,c) {
        console.log("Am I workaholic: "+a);
        console.log("Am I alcoholic: "+b);
        console.log("Am I insomniac: "+c);
    }
Run Code Online (Sandbox Code Playgroud)

当我执行主 js 文件时,我注意到我在一个数组中获得了我的查询响应。

C:\Users\Balajee\Desktop\project\Ultro>node hack
[ { fun: {},
    workaholic: 'Yes',
    alcoholic: 'No',
    insomniac: 'Yes',
    _id: 5706541ba3fe824c2f017680 } ]
Run Code Online (Sandbox Code Playgroud)

当我尝试将这些字段的值设置为变量时,我得到“未定义”

     _id: 5706541ba3fe824c2f017680 } ]
undefined
undefined
undefined
undefined
Am I workaholic: undefined
Am I alcoholic: undefined
Am I insomniac: undefined
Run Code Online (Sandbox Code Playgroud)

那么,如何获取 mongoose 在数组中返回的字段的值?是否可以在没有数组的情况下返回查询?

Ale*_*gan 6

使用findOne()代替find()。这将返回一个 JSON 对象而不是 JSON 对象数组。