Problem:
While pursuing a MERN stack project tutorial on YouTube, I’ve encountered an obstacle in the midst of my progress. The specific issue revolves around the implementation of user registration, a recent addition to my project. I’ve been using ThunderClient to test this feature, and it seems to be causing a challenge. To address this problem effectively, I would appreciate guidance and assistance, particularly in the form of error messages or code snippets related to the registration process.
the result should have been success But I am getting error please help! 🙂
this is the main index file
Index.js
const express = require('express')
const app = express()
const port = 5000
const mongoDB = require("./db")
app.get('/', (req, res) =\> {
res.send('Hello World!')
})
app.use(express.json());
app.use('/api', require("./Routes/CreateUser"));
app.listen(port, () =\> {
console.log(`Example app listening on port ${port}) })
this is the db file
db.js
const mongoose = require('mongoose');
const mongoURI = 'mongodb+srv://Nikita:shani@cluster0.e8wdets.mongodb.net/?retryWrites=true&w=majority'
const mongoDB =async()=>{
await mongoose.connect(mongoURI, { useNewUrlParser: true }, async (err, result) => {
if (err) console.log("---", err);
else {
console.log("connected");
const fetched_data = await mongoose.connection.db.collection("food_items");
fetched_data.find({}).toArray(function (err, data) {
if (err) console.log(err);
else console.log(data);
});
}
});
}
module.exports = mongoDB;
this is the user file
User.js
const mongoose = require('mongoose')
const { Schema } = mongoose;
const UserSchema = new Schema({
name:{
type:String,
required:true
},
location:{
type:String,
required:true,
},
email:{
type:String,
required:true,
unique:true
},
password:{
type:String,
required:true
},
date:{
type:Date,
default:Date.now
},
});
module.exports = mongoose.model('user',UserSchema)
this is the sample file to check whether the data is being stored in the database or not
CreateUser.js
const express = require('express')
const router = express.Router()
const User = require('../models/User')
router.post("/creatuser", async (req, res)=>{
try {
await User.create({
name: "Shyam Das",
password: "123456",
email: "shyamdas12@hotmail.com",
location: "Qwerty edrfef"
})
res.json({success:true});
} catch (error) {
console.log(error);
res.json({success:false});
}
})
module.exports = router;
Solution:
In the CreateUser.js
file there is a typo error:
router.post("/creatuser", async (req, res)=>{...} // You wrote "creatuser"
router.post("/createuser", async (req, res)=>{...} // Change it to "createuser"