2012-06-16 66 views
0

插入MongoDB中服務器的JSON值我想插入(即測試)中產生的數據庫數量,當一個人登錄 以下是代碼文件使用express.js框架

文件:app.js

var express = require('express'); 
var routes = require('./routes'); 
var mongoose = require('mongoose'); 
var db = mongoose.connect('mongodb://localhost/test'); 
var schema = mongoose.Schema; 
var app = module.exports = express.createServer(); 


// Configuration 
app.configure(function() { 
    app.set('views', __dirname + '/views'); 
    app.set('view engine', 'jade'); 
    app.use(express.bodyParser()); 
    app.use(express.methodOverride()); 
    app.use(express.cookieParser()); 
    app.use(express.session({ 
     secret: 'your secret here' 
    })); 

    app.use(app.router); 
    app.use(express.static(__dirname + '/public')); 
}); 

app.configure('development', function() {, 
    app.use(express.errorHandler({ 
     dumpExceptions: true, 
     showStack: true 
    })); 
}); 

app.configure('production', function() { 
    app.use(express.errorHandler()); 
}); 

app.post('/authenticate', routes.authenticate); 
app.get('/login', routes.login); 

// Routes 
app.get('/', routes.home); 
app.post('/', routes.home_post_handler); 
app.post('/putdata', routes.putdata); 

app.listen(3001, function() { 
    console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); 
}); 

文件:index.js

exports.home = function(req, res) { 
    res.redirect('/login'); 
}; 

exports.home_post_handler = function(req, res) { 
    // message will be displayed on console 
    console.log(req.body.message); 

    // send back the json of the message received via the textbox 
    res.json(req.body.message); 
    // or 
    //res.send(200);// send 200 for server processing complete 
}; 

exports.login = function(req, res) { 
    res.render('login', { 
     title: 'login to your system' 
    }); 
}; 

exports.authenticate = function(req, res) { 
    if (req.body.txtlogin == req.body.txtpassword) { 

     var _guid = guidgenerator(); 

     res.json(_guid); 
     db.posts.insert(_guid);// this is the main porblem 

    } 
}; 

function guidgenerator() { 
    var s4 = function() { 
     return (((1 + math.random()) * 0x1000) | 0).tostring(16).substring(1); 
    }; 

    return (s4() + s4() + s4()); 
} 
+0

即時通訊使用expressjs框架請幫我出 – fahad

+0

你能更具體嗎?你得到的實際錯誤是什麼?也考慮簡化您的問題並使用代碼格式。現在很難跟蹤。 – jsalonen

+0

@jsalonen先生我的目標是插入由guidGenerator()生成的值;在index.js文件中放入我的mongodb數據庫中 – fahad

回答

0

您正試圖插入原始類型到數據庫中。當MongoDB將JS對象存儲爲文檔/記錄時,您需要傳遞一個對象作爲insert()的第一個參數。請嘗試以下操作:

if (req.body.txtlogin == req.body.txtpassword) { 
    var guid = guidgenerator(); 

    // Insert an object with a key named "guid" that has the value of var guid 
    db.posts.insert({ "guid": guid }); 
    res.json(guid); 
} 

而且前進請縮進代碼按StackOverflow上的代碼格式化語法。如果沒有格式化,大多數回答者會在瀏覽問題後關閉,反過來讓問題得不到解答。