2

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?

3 Answers 3

6

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

0
4

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)
0
3

I think you should do:

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

because the callback takes err as first param

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.