2016-07-23 111 views
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的特定字段值和存儲到一個變量中的查詢。

回答

0

這是一個可行的中間件的一個例子:

app.get('/quiz', find_ageGroup, function(req, res) { 
    res.render('yourpage.ejs',{ 
     data: data, 
    }) 
}); 
+0

感謝答覆BRO:

function find_ageGroup(req, res, next){ agegroupQuiz.findOne({max_age:item},function(err, agegroup){ if (err) return console.log(err); if(agegroup){ data = agegroup; next(); } else { // Do some form of redirect or render if nothing is found. } }); } 

然後,您可以在您的路線(例如)使用此功能作爲中間件 –

相關問題