Столкнулся с проблемой, что в базу сохраняется только первый юзер (когда база пустая), а все последующие не сохраняются. Ума не приложу, где проблема?
router.post('/register',
userController.validateRegister,
catchErrors(userController.register)
)
контроллер
exports.validateRegister = (req, res, next) => {
// from express-validator
req.sanitizeBody('name')
req.checkBody('name', 'You must supply a name!').notEmpty()
req.checkBody('email', 'That email is not valid!').isEmail()
// https://github.com/chriso/validator.js/
req.sanitizeBody('email').normalizeEmail({
// gmail_remove_dots: true,
remove_dots: false,
remove_extension: false,
gmail_remove_subaddress: false
})
req.checkBody('password', 'Password cannot be blank!').notEmpty()
req.checkBody('password-confirm', 'Confirmed password cannot be blank!').notEmpty()
req.checkBody('password-confirm', 'Passwords do not match!').equals(req.body.password)
const errors = req.validationErrors()
if (errors) {
req.flash('error', errors.map(err => err.msg))
// repopulate filled fields if error
res.render('register', { body: req.body, flashes: req.flash() })
return // stop the function
}
next()
}
exports.register = async (req, res, next) => {
const user = new User({ email: req.body.email, name: req.body.name })
const register = promisify(User.register, User)
await register(user, req.body.password)
next()
}
passport.js
const passport = require('passport')
const mongoose = require('mongoose')
const User = mongoose.model('User')
passport.use(User.createStrategy())
passport.serializeUser(User.serializeUser())
passport.deserializeUser(User.deserializeUser())
модель
const mongoose = require('mongoose')
const Schema = mongoose.Schema
mongoose.Promise = global.Promise
const md5 = require('md5')
const validator = require('validator')
const mongodbErrorHandler = require('mongoose-mongodb-errors')
const passportLocalMongoose = require('passport-local-mongoose')
const userSchema = new Schema ({
email: {
type: String,
unique: true,
lowercase: true,
trim: true,
validate: [validator.isEmail, 'Invalid email address!'],
required: 'Please provide email address'
},
name: {
type: String,
required: 'Please provide a name',
trim: true
}
})
userSchema.plugin(passportLocalMongoose, { usernameField: 'email' })
userSchema.plugin(mongodbErrorHandler)
module.exports = mongoose.model('User', userSchema)