Ritesh Kumar
Ritesh Kumar

Reputation: 79

how i get single field value from mongodb collections using node js

I am trying to find single field value from my collection level. But When I Consoled it gives an undefined. I also debug this line of code, but it gives an error in node-inspector "Runtime.getProperties failed. Internal error: TypeError: Cannot read property 'getters' of undefined". I do not understand what is going on and how I get my single value from my level collection field. My requirement to fetch only single value from level schema, level_num field

1). This is my node js

  this.levelChange = function(req, res, next){

  try{

    var query = {age:5};
    QuizLevel.find(query).exec(function(err, result){
      if(err) return next(err);
      var a = result.min_score;
      console.log(a);
      res.send(a);
    });
        }catch(err){
            console.log("You have error in you code");
            return next(err);
        }
    }; 

2). This is my level schema

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

3). 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
}

Upvotes: 1

Views: 3774

Answers (2)

Libu Mathew
Libu Mathew

Reputation: 2996

Actually the 'find()' return an array not an object . So just replace the code var a = result[0].min_score; with var a = result[0].min_score;

Otherwise you can use the below code to get all 'min_scores' with age=5

this.levelChange = function(req, res, next){
  try {
    var query = {age:5};
    QuizLevel.find(query,{min_score:1}).exec(function(err, result){
      if(err) return next(err);
      var a = result;
      console.log(a);
      res.send(a);
    });
  }
  catch(err){
     console.log("You have error in you code");
      return next(err);
   }
};

Upvotes: 0

Joe
Joe

Reputation: 82554

replace

var a = result.min_score;

with

var a = result[0].min_score;

find returns a collection. If you only want one record try

QuizLevel.findOne(query)

Upvotes: 4

Related Questions