0

我想在有人登录时将生成的数字插入数据库(即测试)以下是代码文件

文件: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());
}
4

1 回答 1

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 的代码格式语法缩进您的代码。如果没有格式化,大多数回答者在浏览问题后会被关闭,从而使您的问题得不到回答。

于 2012-06-16T21:24:44.450 回答