Это пример сайта, который я создал на базовом сервере Node.js.Я могу успешно публиковать сообщения, создавать пользователя по заданной схеме и «сохранять» в базе данных;однако сохранение не возвращает объект пользователя и не может быть найдено в моей реальной базе данных.Соединение также возвращается как успешное.
main.js
const session = require('express-session');
const pug = require('pug');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const User = require('./schema.js');
const app = express();
var path = require('path');
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient('mongodb://localhost:27017');
var db;
client.connect((err, client) => {
if (err) {
console.log(err);
}
else if (!err) {
db = client.db('node');
console.log('Connected to Mongodb');
client.close()
}
});
app.engine('pug', require('pug').__express)
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended : true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'styles')));
app.use(session({secret: 'testing',saveUninitialized: true,resave: true}));
//root directory get response
app.get('/', (req, res) => {
res.render('homepage', {
title : 'Homepage',
req : req
});
});
//register directory get response
app.get('/register', (req, res) => {
res.render('register', {
title : 'Register',
req: req
});
});
//profile directory get response
app.get('/profile', (req, res) => {
res.render('profile', {
title: 'Profile',
email: req.session.email,
username: req.session.username,
req: req
});
});
//login directory get response
app.get('/login', (req, res) => {
res.render('login', {
title: 'Login',
req: req
})
})
//register directory post request
app.post('/register', (req, res) => {
console.log(req.body);
if(req.body.username && req.body.email && req.body.password){
var user = User({
email : req.body.email,
username : req.body.username,
password : req.body.password
});
console.log(user);
user.save((err) => {
user.markModified('password')
console.log("Trying to save")
console.log(user)
if(err){
console.log(err);
} else {
var sess = req.session;
sess.email = req.body.email;
console.log("Saved")
res.redirect('/profile')
}
});
}
});
//login directory post request
app.post('/login', (req, res) => {
console.log(req.body);
if(req.body.username && req.body.password){
var sess = req.session;
sess.username = req.body.username;
res.redirect('/profile')
}
})
const server = app.listen(8000, () => {
console.log(`Express running → PORT ${server.address().port}`);
});
schema.js
const bcrypt = require('bcrypt');
var UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
trim: true
},
username: {
type: String,
unique: true,
required: true,
trim: true
},
password: {
type: String,
unique: false,
required: true,
trim: true
}
});
UserSchema.pre('save', function(req, err, next) {
var user = this;
bcrypt.genSalt(10, (err, salt) => {
if(err){
return next(err);
}
bcrypt.hash(user.password, salt, (err, hash) => {
if(err){
return next(err);
}
user.password = hash;
console.log(hash);
next()
});
});
});
var User = mongoose.model('User', UserSchema);
module.exports = User;