1
我試圖查詢(獲取)MongoDB的一個集合的單個字段值,並且我想使用節點js將它存儲在一個變量中我不明白我執行查詢以便獲取特定的字段值並存儲到變量中。在MongoDB中使用nodejs獲取特定的字段值的查詢
1).Node JS
var agegroupQuiz = require('../models/agegroup.js');
exports.agegroupController = function(req,res,next){
try{
var query = {max_age:item}; max_age value is 5 in my mongo database
var age = agegroupQuiz.findOne(query,function(err,data){
if(err){
console.log(err);
}
res.send(data);
});
if(age===5){
console.log(age); //this will show me the value of stored in mongodb database.
return next(err);
}
else{console.log("error in your code");}
}catch(err){
console.log('Error While Saving the result ' +err);
return next(err);
}
}
2).Mongodb架構
This is my age schema inside models (../models/agegroup.js)
module.exports = (function AgeGroupSchema() {
var Schema = mongoose.Schema;
var AgeGroupSchema = new Schema({
max_age:{type:Number} //I want this value is stored into my age variable.
});
var AgeGroup = mongoose.model('agegroups', AgeGroupSchema);
return AgeGroup;
})();
所以,我需要,其獲取從MongoDB的特定字段值和存儲到一個變量中的查詢。
感謝答覆BRO:
然後,您可以在您的路線(例如)使用此功能作爲中間件 –