0

I have to try to fetch a field value from MongoDB using Node.js. But it shows me undefined in my console. My requirement is to print the data in the console or browser from MongoDB using Node.js.

1). This is my node js

this.levelChange = function(req, res, next){
    try{
        var query = {'level_num':2};
        QuizLevel.find(query,function(err,data){
            var a = data.min_score;
            console.log(a);
            res.send(a);
        });
    }catch(err){
        console.log("Error");
        return next(err);
    }
};

2). This is my js-schema

{
    _id:{type:String},
    age:{type:Number},
    level_num:{type:String},
    min_score:{type:String},
    max_questions:{type:String}
}

3).This is my console output

undefined

4). This is my JSON data

{
  "age":5,
  "level_num":1,
  "min_score":10,
  "max_questions":30
},
{
  "age":5,
  "level_num":2,
  "min_score":12,
  "max_questions":33
}
2
  • console.log(data); see output in console, is data contains your column or not? Commented Aug 22, 2016 at 6:37
  • you are retrieving multiple records is database so you have to use loop get data or you can also use index like data[0].min_score; Commented Aug 22, 2016 at 6:58

2 Answers 2

2

Simply use findOne(find return an array of document) with a project field(return only desired fields).

And don't forget to check the err field !

try{
    var query = {'level_num':2};
    QuizLevel.findOne(query,{min_score: 1}, function(err,data){
        if(err || !data)
        {
           console.log(err);
           return next(err);
        }
        else
        {
          var a = data.min_score;
          console.log(a);
          res.send(a);
        }
    });
}catch(err){
    console.log("Error");
    return next(err);
}
Sign up to request clarification or add additional context in comments.

Comments

0

I might be incorrect but it looks like you're trying to access object property while the result is a collection, see:

data.min_score // => [{ ... }, { ... }].min_score

vs

data[0].min_score

What you want to achieve is something like:

var scores = data.map((function (item) {
  return item.min_score;
});

console.log(scores);

You can always check the type of result with console.log(typeof data) or simply write console.log(data), sometimes console.log(Object.keys(data)) come in handy as well for simple debugging not to mention node-inspector.

1 Comment

i am getting this [ undefined ]

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.