1

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
}

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

i have same problem. Using findOne i am not getting the value?
Athi, I would verify my query is returning results. Test the query in the mongo shell, mongodb compass, or any other testing tool
i got it using toObject()
0

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

Comments

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.