i'll keep it as short as possible. I've used this guide to use MongoDB,NodeJS,Express,Mongoose in my project: https://github.com/joeythelantern/Typescript-Quickstart-Projects/tree/main/typescript-mongoose-quickstart
When i try to use a POST to add user(using Postman >> adding as json with all the parameters) it throw the 'title' error. Im fairly new to TypeScript and tried to find an answer for several days now, hence asking for help.
Thank you in advance.
The Whole error:
TypeError: Cannot read property 'userid' of undefined
at Object.createUser (G:\Projects\React\first\src\Controllers\user.ts:9:17)
at Layer.handle [as handle_request] (G:\Projects\React\first\node_modules\express\lib\router\layer.js:95:5)
at next (G:\Projects\React\first\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (G:\Projects\React\first\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (G:\Projects\React\first\node_modules\express\lib\router\layer.js:95:5)
at G:\Projects\React\first\node_modules\express\lib\router\index.js:281:22
at Function.process_params (G:\Projects\React\first\node_modules\express\lib\router\index.js:335:12)
at next (G:\Projects\React\first\node_modules\express\lib\router\index.js:275:10)
at Function.handle (G:\Projects\React\first\node_modules\express\lib\router\index.js:174:3)
at router (G:\Projects\React\first\node_modules\express\lib\router\index.js:47:12)
EDIT: the error specifies userid from the Controller.
let { userid, email, password, fname, lname, restrict } = req.body;
Controller:
const createUser = (req: Request, res: Response, next: NextFunction) => {
let { userid, email, password, fname, lname, restrict } = req.body;
const user = new User({
_id: new mongoose.Types.ObjectId(),
userid,
email,
password,
fname,
lname,
restrict
});
return user
.save()
.then((result) => {
return res.status(201).json({
user: result
});
})
.catch((error) => {
return res.status(500).json({
message: error.message,
error
});
});
};
Route:
const router = express.Router();
router.post('/create/user', controller.createUser);
router.get('/get/users', controller.getAllUsers);
export default router;
Model:
const UserSchema: Schema = new Schema(
{
userid: { type: Number, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
fname: { type: String, required: true },
lname: { type: String, required: true },
restrict: { type: Number, required: true },
organs: [
{
orgid: { type: Number, required: false },
empnumber: { type: Number, required: false },
lvl: { type: Number, required: false }
}
]
},
{
timestamps: true
}
);
export default mongoose.model<IUser>('User', UserSchema);
CodePudding user response:
The problem wasn't in any of this code, it was in the server file.
OLD
express.json();
express.urlencoded({ extended: false });
FIX
router.use(express.json());
router.use(express.urlencoded({ extended: false }));