2016-04-28 114 views
0

我只想檢查數據庫中是否存在密鑰,但是當我嘗試查詢它時,我只能得到NULL。如何在nodejs中用moongoose查詢mongoDB中的數據

這是我invite.js

var mongoose = require('mongoose'); 
mongoose.createConnection('mongodb://localhost/invitation'); 

var db2 = mongoose.createConnection; 

// User Schema 
var InvitationSchema = mongoose.Schema({ 
    key: { 
     type: String, 
     index: true 
    }, 
    used: { 
     type: String 
    } 
}); 

var Invitation = module.exports = mongoose.model('Invitation', InvitationSchema); 

module.exports.getUsedByKey = function(id, callback){ 
    var query = {used: key}; 
    Invitation.findById(query, callback); 
}; 

module.exports.getInvitationByKey = function(key, callback){ 
    var query = {key: key}; 

    Invitation.findOne(query, callback); 
    console.log('keythingy ' + callback); 
}; 

這是我嘗試使用功能:

function checkKey(key, res) { 

    Invitation.getInvitationByKey(key, function(err, key2) { 
    //console.log('key: ' + key + '\nkey2: ' + key2.key) 
    if (err) throw err; 
    if (key2 !=null) { 
     return key2.key; 
    } else { 
     return false; 
    } 
    }) 
} 

回答

0

使用在寫的NodeJS代碼下面的最佳途徑。貓鼬。

讓一個JavaScript類爲像MongoDB的連接 - > db.js

var mongoose = require('mongoose'); 
mongoose.connect('mongodb://localhost/invitation'); 

var Schema = mongoose.Schema; 

// User Schema 
var InvitationSchema = mongoose.Schema({ 
    key: { 
     type: String, 
     index: true 
    }, 
    used: { 
     type: String 
    } 
}, { 
    collection: 'Invitation' 
}); 

module.exports.Invitation = mongoose.model('Invitation', InvitationSchema); 

再拍從集合中獲取數據JavaScript類 - > invitation.js

var db = require('db.js'); 

module.exports.Initation = { 

    getInvitationByKey : function(key, callback) { 
     var query = {key: key}; 
     db.Invitation.findOne(query, function(err, result){ 
      console.log("Result : ", result, ", Error : ", err); 
      callback(err, result); 
     }); 
    } 
} 

製作路線的JavaScript class - > invitation_route.js

var express = require('express'); 
var router = express.Router(); 
var invitation = require('invitation.js').Initation; 

router.get('/get/:key', function(req, res, next) { 
    invitation.getInvitationByKey(req.params.key, function(err, result){  
     if (err) { 
      console.log(' Error : ', err); 
      res.body(err); 
     } else { 
      console.log(' Result : ' + JSON.stringify(result)); 
      res.send(result); 
     }; 
    }); 
}); 
+0

我還是不明白如何使用這個...假設我已經完成了陳ges,但現在我需要這個「關鍵」,它應該在user.js中返回。我怎麼做? – Emil

+0

對不起。我與你共享一個RestAPI示例意味着你將在請求參數中從客戶端發送關鍵值。 –