Reputation: 992
I'm developing a node.js app with express and mongoDb and mongoose. The app saves the user in the code below with no problem, but in this code it always console error even if the process is success, and the user is saved.
I'm trying to make flash messages and validation but I can't go ahead with this problem.
Also, I'm not sure if I'm using the right post method or not(should I use res.status(500).send('error')) inside the post?
newUser.save().then(function (error) {
if (error) {
console.log('error') // always prints this
} else {
console.log('success')
}
})
the full code
var User = require('../models/User')
var router = require('express').Router()
router.route('/user/signup')
.get(function (request, response) {
// render the form
response.render('user/signup')
})
.post(function (request, response) {
var username = request.body.name
var password = request.body.password
var newUser = new User({
name: username,
password: password
})
newUser.save().then(function (error) {
if (error) {
console.log('error')
} else {
console.log('success')
}
})
response.redirect('/')
})
Upvotes: 1
Views: 1368
Reputation: 2307
I think you want to pass the function directly to save() as the callback
newUser.save(function (err, user) {
if (err) ..
})
With the approach you're currently taking, I think you'll want to use catch
newUser.save().then(function (user) }})
.catch((err) => ...);
Upvotes: 1