When I try to pass the post request in the application, it is not working. When I try to post data using postman, data is not passing, and I get the following values as output.
"_id": "615f2fe2fc52303bdb758e93", "saltSecret": "$2a$10$AmJCbqiunWY2S8kVBbx.a.", "__v": 0
These are my codes.
app.js
require("./config/config");
require("./models/db");
const express = require("express");
const bodyParse = require("body-parser");
const cors = require("cors");
const rtsIndex = require("./route/index.router");
var app = express();
app.use(bodyParse.json());
app.use(cors());
app.use("/api", rtsIndex);
app.listen(process.env.PORT, () =>
console.log(`Server started at port : ${process.env.PORT}`)
);
studentModel.js
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
var studentScheme = new mongoose.Schema({
fullname: {
type: String,
},
email: {
type: String,
},
password: {
type: String,
},
saltSecret: String,
});
studentScheme.pre("save", function (next) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(this.password, salt, (err, hash) => {
this.password = hash;
this.saltSecret = salt;
next();
});
});
});
mongoose.model("Student", studentScheme);
studentController.js
const mongoose = require("mongoose");
const Student = mongoose.model("Student");
module.exports.resgiter = (req, res, next) => {
var student = new Student();
student.fullname = req.body.fullname;
student.email = req.body.email;
student.password = req.body.password;
student.save((err, doc) => {
if (!err) res.send(doc);
});
};
router.js
const express = require("express");
const router = express.Router();
const ctrlStudent = require("../controller/student.controller");
router.post("/register", ctrlStudent.resgiter);
module.exports = router;
Please somebody help me; I don't understand what's wrong with my code
CodePudding user response:
Mostly it is always preferred to use async - await
whenever it's like there is a promise (not the exact promise in nodejs , just a term I used here ) as such which it returns.
So by using async - await
, I do not know how you data is stored in your database; but you can try out the code below and check whther that works or not:
const mongoose = require("mongoose");
const Student = mongoose.model("Student");
module.exports.resgiter = async (req, res, next) => {
var student = new Student({
fullname: req.body.fullname,
email: req.body.email,
password: req.body.password,
});
await student.save((err, doc) => {
if (!err) {
console.log("Saving the document...")
res.send(doc);
}
});
};
You can refer to the links below for async - await
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
https://nodejs.dev/learn/modern-asynchronous-javascript-with-async-and-await