I am trying to wrote RESTFull api with express and mongodb . sections for registraion and login are work properly but when I trying to updatOneById it dosent work .and send you can update only uor accout i delete if cluse but it still same and doesnt work .
index.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
dotenv.config();
mongoose.connect(
process.env.ACCESS_KEY,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("Connected to MongoDB");
}
);
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.listen(8800, () => {
console.log("Backend server is running!");
});
and these are my routers
first is Auth.js
const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//REGISTER
router.post("/register", async (req, res) => {
try {
//generate new password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
//create new user
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: hashedPassword,
});
//save user and respond
const user = await newUser.save();
res.status(200).json(user);
} catch (err) {
res.status(500).json(err)
}
});
//LOGIN
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
!user && res.status(404).json("user not found");
const validPassword = await bcrypt.compare(req.body.password, user.password)
!validPassword && res.status(400).json("wrong password")
res.status(200).json(user)
} catch (err) {
res.status(500).json(err)
}
});
module.exports = router;
seconde is user router
const User = require("../models/User");
const router = require("express").Router();
const bcrypt = require("bcrypt");
//update user
router.put("/:id", async (req, res) => {
if (req.body.userId === req.params.id || req.body.isAdmin) {
if (req.body.password) {
try {
const salt = await bcrypt.genSalt(10);
req.body.password = await bcrypt.hash(req.body.password, salt);
} catch (err) {
return res.status(500).json(err);
}
}
try {
const user = await User.findByIdAndUpdate(req.params.id, {
$set: req.body,
});
res.status(200).json("Account has been updated");
} catch (err) {
return res.status(500).json(err);
}
} else {
return res.status(403).json("You can update only your account!");
}
});
//delete user
router.delete("/:id", async (req, res) => {
if (req.body.userId === req.params.id || req.body.isAdmin) {
try {
await User.findByIdAndDelete(req.params.id);
res.status(200).json("Account has been deleted");
} catch (err) {
return res.status(500).json(err);
}
} else {
return res.status(403).json("You can delete only your account!");
}
});
//get a user
router.get("/:id", async (req, res) => {
try {
const user = await User.findById(req.params.id);
const { password, updatedAt, ...other } = user._doc;
res.status(200).json(other);
} catch (err) {
res.status(500).json(err);
}
});
//follow a user
router.put("/:id/follow", async (req, res) => {
if (req.body.userId !== req.params.id) {
try {
const user = await User.findById(req.params.id);
const currentUser = await User.findById(req.body.userId);
if (!user.followers.includes(req.body.userId)) {
await user.updateOne({ $push: { followers: req.body.userId } });
await currentUser.updateOne({ $push: { followings: req.params.id } });
res.status(200).json("user has been followed");
} else {
res.status(403).json("you allready follow this user");
}
} catch (err) {
res.status(500).json(err);
}
} else {
res.status(403).json("you cant follow yourself");
}
});
//unfollow a user
router.put("/:id/unfollow", async (req, res) => {
if (req.body.userId !== req.params.id) {
try {
const user = await User.findById(req.params.id);
const currentUser = await User.findById(req.body.userId);
if (user.followers.includes(req.body.userId)) {
await user.updateOne({ $pull: { followers: req.body.userId } });
await currentUser.updateOne({ $pull: { followings: req.params.id } });
res.status(200).json("user has been unfollowed");
} else {
res.status(403).json("you dont follow this user");
}
} catch (err) {
res.status(500).json(err);
}
} else {
res.status(403).json("you cant unfollow yourself");
}
});
module.exports = router;
**and this is my schema model **
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
require: true,
min: 3,
max: 20,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
profilePicture: {
type: String,
default: "",
},
coverPicture: {
type: String,
default: "",
},
followers: {
type: Array,
default: [],
},
followings: {
type: Array,
default: [],
},
isAdmin: {
type: Boolean,
default: false,
},
desc: {
type: String,
max: 50,
},
city: {
type: String,
max: 50,
},
from: {
type: String,
max: 50,
},
relationship: {
type: Number,
enum: [1, 2, 3],
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
finally I find that .all of my code is ok but the problem is my cluster on mongodb.
you have to delete your cluster and run it again the problem will be solved .
Related
Hey I am testing on postman as an admin to add category on my project, I have successfully created admin user and login, but when I tried to add category, postman say: TypeError: Cannot read properties of undefined (reading 'role') can anyone help?
Here is my user model:
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const userSchema = new mongoose.Schema(
{
firstName: {
type: String,
required: true,
trim: true,
},
lastName: {
type: String,
required: true,
trim: true,
},
email: {
type: String,
required: true,
trim: true,
unique: true,
},
password: {
type: String,
required: true,
},
role: {
type: String,
enum: ["user", "admin"],
default: "user",
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", userSchema);
here is my auth middleware:
const jwt = require("jsonwebtoken");
const User = require("../models/user");
const { signupUser, loginUser } = require("../controller/adminauth");
exports.auth = (req, res, next) => {
try {
if (req.header.authorization) {
const token = req.header.authorization.split("")[1];
const isCustomAuth = token.length < 500;
let decodeData;
if (token && isCustomAuth) {
decodeData = jwt.verify(token, process.env.JWT_SECRET);
req.UserId = decodeData?.id;
} else {
decodeData = jwt.decode(token);
req.UserId = decodeData?.sub;
}
}
} catch (error) {
console.log(error);
// res.status(400).json({ message: "Authorization required" });
} next ()
};
exports.adminMiddleware = (req, res, next) => {
if (!req.userId.role === "admin") {
return res.status(400).json({ message: "Access denied" });
}
next();
};
Here is my admin auth controller:
const User = require("../models/user");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
exports.loginUser = async (req, res) => {
const { email, password } = req.body;
try {
const existingUser = await User.findOne({ email });
if (!existingUser) {
return res.status(400).json({ message: "User does not exists." });
}
if (!existingUser.role === "admin") {
return res.status(400).json({ message: "User is not admin." });
}
const isPasswordCorrect = await bcrypt.compare(
password,
existingUser.password
);
if (!isPasswordCorrect)
return res.status(400).json({ message: "Invalid credentials." });
const token = jwt.sign(
{
email: existingUser.email,
id: existingUser._id,
role: existingUser.role,
},
process.env.JWT_SECRET,
{ expiresIn: "3d" }
);
res.status(200).json({ result: existingUser, token });
} catch (error) {
console.log(error);
}
};
exports.signupUser = async (req, res) => {
const { firstName, lastName, email, password, confirmPassword } = req.body;
try {
const existingUser = await User.findOne({ email });
if (existingUser)
return res.status(400).json({ message: "Admin already exists." });
if (!password == confirmPassword)
return res.status(400).json({ message: "Password don't match" });
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({
email,
password: hashedPassword,
firstName,
lastName,
role: "admin",
});
const token = jwt.sign(
{ email: result.email, id: result._id, role: result.role },
process.env.JWT_SECRET,
{ expiresIn: "3d" }
);
res.status(200).json({ result, token });
} catch (error) {
console.log(error);
}
};
Here is my category route:
const express = require("express");
const { addCategory, getCategories } = require("../controller/category");
const { auth, adminMiddleware } = require("../middleware/auth");
const router = express.Router();
router.post("/category/create", auth, adminMiddleware, addCategory);
router.get("/category/getcategory", getCategories);
module.exports = router;
In your auth middleware,
change your exports.auth with the following code:
exports.auth = (req, res, next) => {
try {
if (req.header.authorization) {
const token = req.header.authorization.split("")[1];
const isCustomAuth = token.length < 500;
let decodeData;
if (token && isCustomAuth) {
decodeData = jwt.verify(token, process.env.JWT_SECRET);
req.UserId = decodeData||{}; //change this line
} else {
decodeData = jwt.decode(token);
req.UserId = decodeData?.sub;
}
}
} catch (error) {
console.log(error);
res.status(400).json({ message: "Authorization required" });
} next ()
};
I am trying postman for signup a user, {"firstName": "John", "lastName":"zoe", "email":"aaa#gmail.com", "password":"123465"} but the postman gives me this 500 error: {
"message": "Something went wrong"
},
I could not figure out is my logic wrong, or something is missing, I did not use the validator package, as I am not sure how to use it, is that the problem? can anyone pls help?
here is my code, in the server.js file:
const express = require("express");
const env = require("dotenv");
const { response } = require("express");
const app = express();
const mongoose = require("mongoose");
//routes
const authRoutes = require("./routes/auth");
const adminRoutes = require("./routes/adminauth");
const categoryRoutes = require("./routes/category");
//enviorment variables
env.config();
app.use(express.json());
mongoose
.connect(
`mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASSWORD}#cluster0.h28xczp.mongodb.net/${process.env.MONGODB_DATABASE}?retryWrites=true&w=majority`
)
.then(() => {
console.log("Database connection established");
});
app.use("/api", authRoutes);
app.use("/api", adminRoutes);
app.use("/api", categoryRoutes);
app.listen(process.env.PORT, () => {
console.log(`server is running at ${process.env.PORT}`);
});
In my routes file:
const express = require("express");
const router = express.Router();
const { signupUser, loginUser } = require("../controller/auth");
const { auth, userMiddleware, adminMiddleware } = require("../middleware/auth");
//login route
router.post("/login", loginUser);
//signup route
router.post("/signup", signupUser);
module.exports = router;
Middleware file:
const jwt = require("jsonwebtoken");
const User = require("../models/user");
exports.auth = (req, res, next) => {
try {
const token = req.header.authorization.split("")[1];
const isCustomAuth = token.length < 500;
let decodeData;
if (token && isCustomAuth) {
decodeData = jwt.verify(token, env.Process.JWT_SECRET);
req.UserId = decodeData?.id;
} else {
decodeData = jwt.decode(token);
req.UserId = decodeData?.sub;
}
next();
} catch (error) {}
};
exports.userMiddleware = (req, res, next) => {
if (req.user.role !== "user") {
return res.status(400).json({ message: "User access denied" });
}
next();
};
exports.adminMiddleware = (req, res, next) => {
if (req.user.role !== "admin") {
return res.status(400).json({ message: "Access denied" });
}
next();
};
In my controller file:
const User = require("../models/user");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
exports.loginUser = async (req, res) => {
const { email, password } = req.body;
try {
const existingUser = await User.findOne({ email });
if (!existingUser)
return res.status(400).json({ message: "User does not exists." });
const isPasswordCorrect = await bcrypt.compare(
password,
existingUser.password
);
if (!isPasswordCorrect)
return res.status(400).json({ message: "Invalid credentials." });
const token = jwt.sign(
{ email: existingUser.email, id: existingUser._id },
process.env.JWT_SECRET,
{ expiresIn: "3d" }
);
res.status(200).json({ result: existingUser, token });
} catch (error) {
res.status(500).json({ message: "Something went wrong" });
}
};
exports.signupUser = async (req, res) => {
const { firstName, lastName, email, password, confirmPassword } = req.body;
try {
const existingUser = await User.findOne({ email });
if (existingUser)
return res.status(400).json({ message: "User already exists." });
if (!password == confirmPassword)
return res.status(400).json({ message: "Password don't match" });
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({
email,
password: hashedPassword,
firstName,
lastName,
});
const token = jwt.sign(
{ email: result.email, id: result._id },
process.env.JWT_SECRET,
{ expiresIn: "3d" }
);
res.status(200).json({ result, token });
} catch (error) {
res.status(500).json({ message: "Something went wrong" });
}
};
My user model file:
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const userSchema = new mongoose.Schema(
{
firstName: {
type: String,
required: true,
trim: true,
},
lastName: {
type: String,
required: true,
trim: true,
},
email: {
type: String,
required: true,
trim: true,
unique: true,
},
password: {
type: String,
required: true,
},
id: {
type: String,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", userSchema);
In the middleware, this line contains a wrong reference to JWT_SECRET.
decodeData = jwt.verify(token, env.Process.JWT_SECRET);
Should be
decodeData = jwt.verify(token, process.env.JWT_SECRET);
The application throws an unhandled promise rejection error when trying to connect DB, which means it can operate without a DB connection and then throw that error.
So, to handle that, you can rewrite your code to this.
mongoose.connect('mongodb://localhost:27017/usersdb', // change with your db url
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
.then(() => {
app.use("/api", authRoutes);
app.listen(process.env.PORT, () => {
console.log("Server has started on port!", process.env.PORT)
})
})
.catch(() => { throw new Error(("Connection error")) });
Also, I successfully ran and tested your application on my local machine. Here is a GitHub link; you can compare.
https://github.com/nairi-abgaryan/express-auth
I want to use auth middleware in expressjs with role based auth check or without role based.
after login, i am passing access token as bearer token, but authentication doesn't seems to work.
this is auth middleware
const passport = require('passport');
const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const { roleRights } = require('../config/roles');
const verifyCallback = (req, resolve, reject, requiredRights) => async (err, user, info) => {
if (err || info || !user) {
return reject(new ApiError(httpStatus.UNAUTHORIZED, 'Please authenticate'));
}
req.user = user;
if (requiredRights.length) {
const userRights = roleRights.get(user.role);
const hasRequiredRights = requiredRights.every((requiredRight) => userRights.includes(requiredRight));
if (!hasRequiredRights && req.params.userId !== user.id) {
return reject(new ApiError(httpStatus.FORBIDDEN, 'Forbidden'));
}
}
resolve();
};
const auth = (...requiredRights) => async (req, res, next) => {
return new Promise((resolve, reject) => {
passport.authenticate('jwt', { session: false }, verifyCallback(req, resolve, reject, requiredRights))(req, res, next);
})
.then(() => next())
.catch((err) => next(err));
};
module.exports = auth;
here in router, i am using middleware like this.
const express = require('express');
const auth = require('../../middlewares/auth');
const validate = require('../../middlewares/validate');
const userValidation = require('../../validations/user.validation');
const userController = require('../../controllers/user.controller');
const router = express.Router();
router.get('/', auth(), userController.getUsers);
module.exports = router;
here i am passing accesstoken like this in request
GET http://localhost:5000/v1/users HTTP/1.1
Authorization: Bearer *****************(accesstoken-returned-after-login)************************
access token expire time is set to 30 minutes, whenever i pass access token in this request,
i am only getting response "Please Authenticate".
**
passport.js in config
**
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
const config = require('./config');
const { tokenTypes } = require('./tokens');
const { User } = require('../models');
const jwtOptions = {
secretOrKey: config.jwt.secret,
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
};
const jwtVerify = async (payload, done) => {
try {
if (payload.type !== tokenTypes.ACCESS) {
throw new Error('Invalid token type');
}
const user = await User.findById(payload.sub);
if (!user) {
return done(null, false);
}
done(null, user);
} catch (error) {
done(error, false);
}
};
const jwtStrategy = new JwtStrategy(jwtOptions, jwtVerify);
module.exports = {
jwtStrategy,
};
this is user collection schema
const mongoose = require('mongoose');
const validator = require('validator');
const bcrypt = require('bcryptjs');
const { toJSON, paginate } = require('./plugins');
const { roles } = require('../config/roles');
const userSchema = mongoose.Schema(
{
name: {
type: String,
required: true,
trim: true,
},
email: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Invalid email');
}
},
},
password: {
type: String,
required: true,
trim: true,
minlength: 8,
validate(value) {
if (!value.match(/\d/) || !value.match(/[a-zA-Z]/)) {
throw new Error('Password must contain at least one letter and one number');
}
},
private: true, // used by the toJSON plugin
},
role: {
type: String,
enum: roles,
default: 'employee',
},
isEmailVerified: {
type: Boolean,
default: false,
},
},
{
timestamps: true,
}
);
// add plugin that converts mongoose to json
userSchema.plugin(toJSON);
userSchema.plugin(paginate);
userSchema.statics.isEmailTaken = async function (email, excludeUserId) {
const user = await this.findOne({ email, _id: { $ne: excludeUserId } });
return !!user;
};
userSchema.methods.isPasswordMatch = async function (password) {
const user = this;
return bcrypt.compare(password, user.password);
};
userSchema.pre('save', async function (next) {
const user = this;
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, 8);
}
next();
});
const User = mongoose.model('User', userSchema);
module.exports = {
User
};
I just had issue in importing collection schema in my passport.js file. i solved it by doing in passport.js
const { User } = require('../models/user.model');
and everything works as expected.
*I can create new account and also i can login but when i am going to logout that time i will logout but if i am try to login with same email and password but i cannot able to login it is showing me jsonwebtoken error -> {"name":"JsonWebTokenError","message":"jwt must be provided"} *
register.js
This is my register.js file code
app.get("/register", (req, res) => {
// res.send('Hello Arunesh')
res.render("register");
});
app.post("/register", async (req, res) => {
try {
const password = req.body.password;
const cPassword = req.body.cPassword;
if (password === cPassword) {
const registerData = new Register({
firstName: req.body.firstName,
lastName: req.body.lastName,
phone: req.body.phone,
gender: req.body.gender,
email: req.body.email,
age: req.body.age,
password: req.body.password,
confirmPassword: req.body.cPassword,
});
const token = await registerData.generateAuthToken();
console.log('Register Token : ',token);
res.cookie('jwt', token,{
httpOnly:true
})
const register = await registerData.save();
console.log(register);
res.status(201).render("index");
} else {
res.send("Password are not match");
}
} catch (e) {
res.status(400).send(e);
}
});
login.js
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", auth,async (req, res) => {
try {
const email = req.body.email;
const password = req.body.password;
const userEmail = await Register.findOne({ email: email });
const isMatch = await bcrypt.compare(password, userEmail.password);
const token = await userEmail.generateAuthToken();
res.cookie('jwt', token,{
expires:new Date(Date.now()+30000000),
httpOnly:true
})
console.log('Login Token : ',token);
console.log(isMatch);
if (isMatch) {
res.status(201).render("index");
} else {
res.send("Invalid password or email");
}
} catch (e) {
res.status(400).send(e);
}
});
Logout.js
app.get('/logout', auth,async (req, res)=>{
try{
// console.log(req.user);
// Logout for single user
req.user.tokens = req.user.tokens.filter((authToken)=>{
return authToken.token != req.token;
})
// logout from all device
// req.user.tokens = [];
res.clearCookie("jwt");
await req.user.save();
res.render('login');
}catch(e){
console.log(e);
}
})
auth.js
const jwt = require('jsonwebtoken');
const Register = require('../models/registers');
const auth = async (req, res, next)=>{
try{
const token = req.cookies.jwt;
const verifyUser = jwt.verify(token, process.env.SECRET_KEY);
const user = await Register.findOne({_id:verifyUser._id, 'tokens.token':token})
req.token = token;
req.user = user;
next()
}catch(e){
res.send(e)
}
}
module.exports = auth;
**
generateAuthToken
**
registerSchema.methods.generateAuthToken = async function () {
try {
const token = jwt.sign({ _id: this._id.toString() },process.env.SECRET_KEY);
this.tokens = this.tokens.concat({token:token})
await this.save();
return token;
} catch (e) {
console.log(e);
}
};
**
Schema
**
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const registerSchema = new mongoose.Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
phone: {
type: Number,
required: true,
unique: true,
},
gender: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
age: {
type: Number,
required: true,
},
password: {
type: String,
required: true,
},
confirmPassword: {
type: String,
required: true,
},
tokens: [
{
token: {
type: String,
required: true,
},
},
],
});
/********************************************
* Generate Token
********************************************/
registerSchema.methods.generateAuthToken = async function () {
try {
const token = jwt.sign({ _id: this._id.toString() },process.env.SECRET_KEY);
this.tokens = this.tokens.concat({token:token})
await this.save();
return token;
} catch (e) {
console.log(e);
}
};
/********************************************
* Password Hash
********************************************/
registerSchema.pre("save", async function (next) {
if (this.isModified("password")) {
this.password = await bcrypt.hash(this.password, 10);
this.confirmPassword = await bcrypt.hash(this.password, 10);
}
next();
});
const Register = new mongoose.model("Register", registerSchema);
module.exports = Register;
you use auth middleware in /login route, this error happens when the coming token is null or empty ,remove auth middleware from the route like this, I hope the problem is solved with my answer
app.post("/login" , async (req, res) => {...
I'm new to NodeJS,I'm just trying to create a restfull API, but when I try to execute the code by running (npm run dev),it's throwing an error.There are many questions like this one, but no answer could figure out what is wrong in my code.
the error is : app.use() requires a middleware function
this is my index.js
const express = require("express");
const app = express()
const departmentRouter = require("../src/routes/department")
app.use(express.json())
app.use(departmentRouter)
const port = process.env.PORT || 3000;//local machine port 3000
app.listen(port, () => (`Server running on local machine port ${port} 🔥`));
this is the model :
const mongoose = require("mongoose");
const validator = require('validator')
const Department = mongoose.model('Department', {
name: {
type: String,
required: true,
}
,
email: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Invalid email!')
}
}
}
,
createdBy: {
type: String,
default: 'SYS_ADMIN'
}
,
updatedBy: {
type: String,
default: 'SYS_ADMIN'
}
,
createdAt: {
type: Date
// ,
// default: Date.getDate()
}
,
updatedAt: {
type: Date
// ,
// default: Date.getDate()
},
isDeleted: {
type: Boolean,
default: false
}
})
module.exports = Department
this is routes file (department.js)
const express = require("express");
const router = express.Router();
const Department = require("../models/department")
router.get("/v1/departments", async (req, res) => {
try {
const departments = await Department.find({ isDeleted: false })
if (!departments) {
return res.status(404).send()
}
res.status(200).send()
} catch (error) {
res.status(500).send(error)
}
});
router.get("/v1/department/:id", async (req, res) => {
//test if the department exist => by id
const _id = req.params._id
try {
const depatment = await Department.findByid(_id, { isDeleted: false })
if (!depatment) {
return res.status(404).send()
}
res.status(200).send(depatment)
} catch (error) {
res.status(500).send(error)
}
});
router.post("/v1/department", async (req, res) => {
try {
const department = new Department(req.body) //this param is for testing the post methode by sending request from postman
await department.save()
} catch (error) {
res.status(500).send(error)
}
});
router.put("/v1/department/:id", async (req, res) => {
//especially useful when testing the put method using postman
const updates = Object.keys(req.body)
const allowedUpdates = ['name', 'email']
const isValideOperations = updates.every((update) => allowedUpdates.includes(update))
if (!isValideOperations) {
return res.status(400).send({ error: 'Invalid updates' })
}
try {
const _id = req.params.id
const department = await Department.findByIdAndUpdate(_id)
if (!department) {
return res.status(404).send()
}
res.send(department)
} catch (error) {
res.status(500).send(error)
}
})
//Safe delete by updating the field isDeleted to true
router.delete('/v1/department/:id', async (req, res) => {
try {
const _id = req.params.id
const department = await Department.findByIdAndUpdate(_id, { isDeleted: true })
if (!department) {
return res.status(400).send()
}
res.status(200).send(department)
} catch (error) {
res.status(500).send(error)
}
})
In the department.js file, you need to export the router:
module.exports = router