我为每个用户提供了不同的数据库。数据库的名称与用户名相同。我有另一个数据库调用'auth',其中包含用于登录的每个用户的用户名和密码。
所以最初nodejs连接到auth数据库并且基于用户登录,数据库应该相应地改变。
为此,我创建了两个数据库连接conn(用于auth)和conn2(用于特定于用户的数据库)。登录后,用户应重定向到我的主页,其中包含用户特定数据库中指定的数据。
但是,登录后,用户将“undefined_dashboard”重定向到主页作为数据库。我知道问题是由于异步编程造成的。
如何解决?
我已将问题类比代码附加在问题本身中。
文件夹管理:
|node_modules
|routes
|--dashboard.js
|views
|--dashboard_span.ejs
|--index.ejs
|app.js
|models.js
|package.json
app.js:
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var conn = mongoose.createConnection('mongodb://localhost/auth');
var User = conn.model('User', new mongoose.Schema({
username: String,
password: String,
},{collection:'user'}));
var app = express();
app.set('view engine','ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(bodyparser.urlencoded({extended:true}));
app.get('/', function(request, response){
response.render('index.ejs');
});
app.post('/', function(request, response){
User.findOne({username:request.body.username},function(error, user){
if (!user) {
response.render('index.ejs', {error: "Incorrect email / password"});
}
else {
if (user.password === request.body.password) {
global.username = user.username;
response.redirect('/dashboard');
}
else {
response.render('index.ejs', {error: "aIncorrect email / password"});
}
}
global.client_name = global.username;
});
});
database_name = 'mongodb://localhost/'+global.client_name+'_dashboard';
console.log(database_name)
module.exports.conn2 = mongoose.createConnection(database_name);
app.use(require('./routes/dashboard'));
app.listen(3000, function(request, response){
console.log(database_name)
console.log("Server is running at Port 3000");
});
models.js:
var mongoose = require('mongoose');
var app = require('./app');
module.exports.Suspicious = app.conn2.model('Suspicious', new mongoose.Schema({
youtube: Number,
twitter: Number,
googleplus: Number,
facebook: Number,
},{collection: 'sm_total_suspicious_counter'}));
dashboard.js:
var express = require('express');
var models = require('../models');
var router = express.Router();
router.get('/dashboard', function(request, response){
models.Suspicious.findOne({},function(error, suspicious_data){
if (error) { response.send("<h1>Database's fault. The damn thing is not sending data.</h1>") }
response.render('dashboard_span.ejs', {suspicious:suspicious_data});
});
});
module.exports = router;
dashboard_span.ejs:
<html>
<head>
<title>Testing</title>
</head>
<body>
<%= suspicious %>
</body>
</html>
index.ejs:
<!DOCTYPE html>
<html>
<body>
<form method='post'>
Username:<br>
<input type="text" name="username" id='username'>
<br>
Password:<br>
<input type="password" name="password" id='password'>
<button name="submit">Sign In</button>
</form>
</body>
</html>