Balajee Ks
Balajee Ks

Reputation: 359

How to get the value of a field from mongoose mongodb query?

This is a piece of code from my main js file which i'm using to call a function in another js file(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));

This is the js.js file which i'm referencing in the main js file

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);
    }

When i execute the main js file, I notice that I'm getting my query response in an array.

C:\Users\Balajee\Desktop\project\Ultro>node hack
[ { fun: {},
    workaholic: 'Yes',
    alcoholic: 'No',
    insomniac: 'Yes',
    _id: 5706541ba3fe824c2f017680 } ]

When i try to set the value of these fields to variables, I'm getting "undefined"

     _id: 5706541ba3fe824c2f017680 } ]
undefined
undefined
undefined
undefined
Am I workaholic: undefined
Am I alcoholic: undefined
Am I insomniac: undefined

So, how do i fetch the value of the field which is returned by the mongoose in an array? is it possible to return the query without array?

Upvotes: 2

Views: 6888

Answers (3)

Lulylulu
Lulylulu

Reputation: 1264

I think you should do:

exports.myfun = function(err, hackers) {
  // ...
}

because the callback takes err as first param

Upvotes: 3

Alex Logan
Alex Logan

Reputation: 1241

Use findOne() instead of find(). This returns a JSON object rather that array of JSON objects.

Upvotes: 6

Jack Guy
Jack Guy

Reputation: 8523

You can use findOne instead of find. findOne will return a single object that matches your query, instead of an array.

Hacker.findOne({name: "arun"}, fields)

Upvotes: 4

Related Questions