I am trying to create a new hotel by using the below API call.
Here you can see the relevant POST request
I can see that the application is running:
Connected to backend. mongoDB connected! Connected to mongoDB.
Howeverö couldn't access the api/hotels endpoint. Any ideas where I am making a mistake here?
Here is the hotels.js file
import express from "express";
import Hotel from "../models/Hotel.js";
const router = express.Router();
//CREATE
router.post("/api/hotels", async (req,res)=>{
const newHotel = new Hotel(req, body)
try{
const savedHotel = await newHotel.save()
res.status(200).json(savedHotel)
}catch(err){
res.status(500).json(err)
}
})
//UPDATE
router.put("/:id", async (req,res)=>{
try{
const updatedHotel = await Hotel.findByIdAndUpdate(req.params.id, { $set: req.body})
res.status(200).json(updatedHotel)
}catch(err){
res.status(500).json(err)
}
})
//DELETE
//GET
//GET ALL
export default router;
index.js
// import express from "express";
// import dotenv from "dotenv";
import mongoose from "mongoose";
import express from "express";
import authRoute from "./routes/auth.js";
import usersRoute from "./routes/users.js";
import hotelsRoute from "./routes/hotels.js";
import roomsRoute from "./routes/rooms.js";
const app = express();
// dotenv.config()
const connect = async ()=>{
try {
await mongoose.connect('mongodb srv://********@******.mongodb.net/?retryWrites=true&w=majority');
console.log("Connected to mongoDB.")
} catch (error) {
throw error
}
};
mongoose.connection.on("disconnected", ()=>{
console.log("mongoDB disconnected!")
})
mongoose.connection.on("connected", ()=>{
console.log("mongoDB connected!")
})
// middlewares
app.use(express.json())
app.use("api/auth", authRoute);
app.use("api/users", usersRoute);
app.use("api/hotels", hotelsRoute);
app.use("api/rooms", roomsRoute);
app.listen(8800, ()=>{
connect()
console.log("Connected to backend.")
app.get('/', (_, res) => res.send({message: 'Hello from Express'}))
});
CodePudding user response:
Use just router.post("/"
instead of router.post("/api/hotels"
, because now full path for your endpoint is /api/hotels/api/hotels
CodePudding user response:
Looks like the problem could be here:
const newHotel = new Hotel(req, body)
And within the definition of Hotel
. I am assuming that Hotel looks something like this for the sake of the example:
const hotelSchema = new mongoose.Schema({ hotelName: 'string', rooms: 'number' });
export const Hotel = mongoose.model('Hotel', hotelSchema);
When you call an instance of the new Schema it should be done this way:
const newHotel = new Hotel({rooms: 4, hotelName: "Shuraton"})
and not:
const newHotel = new Hotel(req, body)
Anyway, it would be a good practice to validate the request.body
, and sanitize the input before. You can do that with Joi
express-validtor
or ajv
.
Let me know if that helped.