Advanced node and express registration of new users
Here is an example of how to implement user registration using Node.js, Express.js, and a MongoDB database:
Step 1: Set up the project
Create a new Node.js project and install the required dependencies:
npm init -y
npm install express body-parser mongoose
Step 2: Create the database model
Create a new file called user.model.js
and add the following code:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: { type: String, unique: true },
password: String
});
const User = mongoose.model('User', userSchema);
module.exports = User;
This defines a User
model with three fields: name
, email
, and password
.
Step 3: Create the registration route
Create a new file called register.js
and add the following code:
const express = require('express');
const router = express.Router();
const User = require('../models/user.model');
const bcrypt = require('bcrypt');
router.post('/register', (req, res) => {
const { name, email, password } = req.body;
if (!name ||!email ||!password) {
return res.status(400).send({ message: 'All fields are required' });
}
User.findOne({ email }, (err, user) => {
if (err) {
return res.status(500).send({ message: 'Error occurred' });
}
if (user) {
return res.status(400).send({ message: 'Email already exists' });
}
const hashedPassword = bcrypt.hashSync(password, 10);
const newUser = new User({
name,
email,
password: hashedPassword
});
newUser.save((err) => {
if (err) {
return res.status(500).send({ message: 'Error occurred' });
}
res.send({ message: 'User created successfully' });
});
});
});
module.exports = router;
This route handles the registration request by:
- Extracting the
name
,email
, andpassword
from the request body. - Checking if all fields are provided. If not, return a 400 error.
- Checking if the email already exists in the database. If it does, return a 400 error.
- Hashing the password using bcrypt.
- Creating a new
User
document and saving it to the database. - Returning a success message if the user is created successfully.
Step 4: Add the route to the Express app
In your app.js
file, add the following code:
const express = require('express');
const app = express();
const registerRouter = require('./register');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/register', registerRouter);
app.listen(3000, () => {
console.log('Server started on port 3000');
});
This sets up the Express app to use the registerRouter
and listens for incoming requests on port 3000.
Step 5: Test the registration route
Use a tool like Postman or cURL to send a POST request to http://localhost:3000/register
with the following JSON payload:
{
"name": "John Doe",
"email": "[email protected]",
"password": "password123"
}
If the registration is successful, you should receive a response with a success message. If there is an error, you should receive an error message with a 400 or 500 status code.
That's it! You now have a basic user registration system using Node.js, Express.js, and MongoDB.