error ReferenceError:使用mongodb

时间:2017-08-16 18:12:42

标签: node.js mongodb express

我正在尝试使用post方法并在注册期间保存有关用户的信息,但是我收到此错误,有人知道如何解决它吗? 我试图在互联网上搜索,但任何事都适合我。 我的文件的组织是否正确?或者我应该创建另一个名为database.js的文件?我在www.js里面插入了与服务器的连接和数据库的连接,但我不知道它是否正确。 感谢任何可以提供帮助的人......

我的app.js文件

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');


//DB
//var mongo = require('mongodb');

//var server = require('./routes/server');
var index = require('./routes/index');
var Registration = require('./routes/Registration');
var login = require('./routes/login');
var app = express();
//var db = require('./config/challengeskill');

// view engine setup

app.set('views', path.join(__dirname, 'views'));

app.set('view engine', 'ejs');


// uncomment after placing your favicon in /public

//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



app.use('/', index);
app.use('/Registration',Registration);
app.use('/login',login);


app.post('/registrationform', (req, res) => {

db.collection('user').save(req.body, (err,result)=>{
  if(err) return console.log(err)

  console.log('saved to database')
  res.redirect('/')
})
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

我的www.js文件     #!/ usr / bin / env node

/**
 * Module dependencies.
 */

    var app = require('../app');
var debug = require('debug')('challengeskill:server');
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
var db;
var url = 'mongodb://localhost:27017/user';

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);


/**
 * Gconnect DB.
 */

MongoClient.connect(url, function (err, database) {
    if (err) {
    throw err;
    }
    else {
  ///////////////////////////
    database = db;
    console.log("connected to DB");

}
});

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
  console.error(bind + ' requires elevated privileges');
  process.exit(1);
  break;
    case 'EADDRINUSE':
  console.error(bind + ' is already in use');
  process.exit(1);
  break;
default:
  throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

这是我的文件并且有条理

>ChallengeSkill
>>.idea
>>bin
---->www
>>node_modules
>>public
>>routes
---->index.js
---->login.js
---->Registration.js
---->users.js
>>views
---->error.ejs
---->index.ejs
---->login.ejs
---->Registration.ejs
app.js
ChallengeSkill.iml
package.json

2 个答案:

答案 0 :(得分:2)

您的代码很好,但是您将返回的database值分配给名为db的空变量,因此只需交换它们并按预期工作。

答案 1 :(得分:0)

在您的www.js文件中,您可能想要换行

database = db;
像这样:

db = database;