Home > Net >  How can create user in express.js using mongoose
How can create user in express.js using mongoose

Time:08-28

I am trying to create a user in express.js using mongoose. I tried everything but i only get lastName and password i don't know what happened. even in req.body.firstName also have data in but in newUser i only get two value lastName and password

let newUser = new User({
  firstName: req.body.firstName,
  lastName: req.body.lastName,
  email: req.body.email,
  password: req.body.password,
  phone: req.body.phone,
})

bcrypt.genSalt(10, (err, salt) => {
  bcrypt.hash(newUser.password, salt, (err, hash) => {
    if (err) {
      res.status(500).json({ error: err});
    } else{
      newUser.password = hash;
      newUser.save()
       .then(res => {
         res.status(200).json({ message: 'Successfullt created'   })
      })
      .catch((err) => {
        res.status(500).json({ error: err});
      })
   }
 })

})

Model

const mongoose = require('mongoose')
const { Schema } = mongoose

const userModel = new Schema({
   firtName: {
     type: String,
     required: true
   },
   lastName: {
     type: String,
     required: true
   },
   email: {
     type: String,
     required: true
   },
   password: {
     type: String,
     required: true
   },
   phone: {
     type: Number,
     required: true
   }

})

User = mongoose.model('User', userModel)
module.exports = User

CodePudding user response:

This is a typo. firtName should be firstName in your model. Try this:

const userModel = new Schema({
   firstName: {
     type: String,
     required: true
   },
   ...
})

Edit:

Now it showing error " res.status is not a function ".

It's showing that error because the .save() function does not return an object with .status function. It returns the saved document.

Try renaming

.save().then(res => { res.status(200)...

to

.save().then(savedDoc => { res.status(200)...

  • Related