[英]fetch a particular value using node js and mongodb
I have to try to fetch a field value from MongoDB using Node.js. 我必须尝试使用Node.js从MongoDB中获取字段值。 But it shows me
undefined
in my console. 但是它显示我的控制台中
undefined
。 My requirement is to print the data in the console or browser from MongoDB using Node.js. 我的要求是使用Node.js从MongoDB在控制台或浏览器中打印数据。
1). 1)。 This is my node js
这是我的节点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). 2)。 This is my js-schema
这是我的js模式
{
_id:{type:String},
age:{type:Number},
level_num:{type:String},
min_score:{type:String},
max_questions:{type:String}
}
3).This is my console output 3)。这是我的控制台输出
undefined
4). 4)。 This is my JSON data
这是我的JSON数据
{
"age":5,
"level_num":1,
"min_score":10,
"max_questions":30
},
{
"age":5,
"level_num":2,
"min_score":12,
"max_questions":33
}
Simply use findOne(find return an array of document) with a project field(return only desired fields). 只需将findOne(查找返回文档数组)与项目字段一起使用(仅返回所需的字段)。
And don't forget to check the err field ! 并且不要忘记检查err字段!
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);
}
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. 您始终可以使用
console.log(typeof data)
来检查结果的类型,也可以简单地编写console.log(data)
,有时console.log(Object.keys(data))
很方便进行简单的调试,更不用说node -检查员
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.