1

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('/')
 })

1 Answer 1

1

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) => ...);

Source: mongoose docs

Sign up to request clarification or add additional context in comments.

2 Comments

True. Is there a better approach without using catch? Because I want to use express validation with flash messages.
Personally I prefer using async/await: await newUser.save() but I'm unsure if there's a better way atm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.