我第一次使用nodejs和MongoDB,当我想连接数据库时遇到麻烦。
我从mongoosejs读了快速入门,但它仍然不起作用,这是我的代码(现在,我的所有代码只在一个文件中):
/***** Utilities *****/
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
app.listen(8080);
mongoose.connect('mongodb://localhost:8080/users');
var db = mongoose.connection;
db.on('error', function (error) {
console.log('/**************** ERROR **************\\');
console.log(error);
});
db.on('open', function () {
console.log("Hello World!");
});
var Schema = mongoose.Schema;
var UserSchema = new Schema({
pseudo: String,
password: String,
email: String
});
var Users = mongoose.model('users', UserSchema);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/views');
app.use(passport.initialize());
app.use(passport.session());
/***** Passport *****/
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
/***** Building routes *****/
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.post('/', function (req, res) {
var pseudo = req.body.pseudo;
console.log("/******************************\\") console.log(pseudo);
res.send('Hello ' + pseudo + '!');
});
app.get('/users', function (req, res) {
Users.find(function (error, users) {
if (error) console.log(error);
else res.render('users.jade', {
users: users
})
});
})
app.post('/create_user', function (req, res) {
var user = new Users({
pseudo: req.body.pseudo,
password: req.body.password,
email: req.body.email
});
user.save(function (error, user) {
if (error) console.log(error);
else res.render('create_user.jade');
});
});
app.get('/login', function (req, res) {
passport.authenticate('users', {
successRedirect: '/create_user',
failureRedirect: '/login',
}) res.render('login.jade
);
});
我正在尝试从登录页面获取数据并将它们存储到一个mongo数据库中,但是当我启动此文件时,mongo会返回以下消息:
MongoError:服务器localhost:8080套接字已关闭 名称:'MongoError', 消息:'server localhost:8080套接字已关闭'
我真的不知道如何纠正这个错误。 我哪里错了?是因为可能存在异步问题吗?