I have booking schema and i tried to fetch data from this booking database when userid that fetched from the secureStore and tenant_id are matches and the approval field is ‘accepted’.
problem:it show me ERROR Error fetching bookings: [Error: HTTP error! Status: 404] this error several times
approaches: i tried just with when the approval field is accepted and it works
this is my codes
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bookingSchema = new Schema(
{
property_id: {
type: Schema.Types.ObjectId,
ref: "property",
required: true,
},
tenant_id: {
type: Schema.Types.ObjectId,
ref: "user",
required: true,
},
owner_id: {
type: Schema.Types.ObjectId,
ref: "user",
required: true,
},
start_date: { type: String, required: true },
end_date: { type: String, required: true },
approval: { type: String, default: "Pending" },
message: { type: String },
},
{
timestamps: true,
}
);
const Booking = mongoose.model("Booking", bookingSchema);
module.exports = Booking;
```//The end point
app.get(“/bookings/:tenantId”, async (req, res) => {
const { tenantId } = req.params;
try {
const bookings = await Booking.find({
tenant_id: tenantId,
approval: “accepted”,
});
if (!bookings || bookings.length === 0) {
return res
.status(404)
.json({ message: "No accepted bookings found for this tenant." });
}
res.status(200).json(bookings);
} catch (error) {
console.error(“Error fetching bookings:”, error);
res
.status(500)
.json({ message: “Internal Server Error”, error: error.message });
}
});
//client side code
const [bookings, setBookings] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
const fetchUserId = async () => {
try {
const userId = await SecureStore.getItemAsync(“user_id”);
if (!userId) {
setError(“User ID not found”);
return null;
}
return userId;
} catch (err) {
setError(“Error fetching user ID”);
console.error(“Error fetching user ID:”, err);
return null;
}
};
const fetchBookings = async (userId) => {
try {
const response = await fetch(
`http://10.139.165.187:8000/bookings/${userId}`
);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
setBookings(data);
} catch (err) {
setError(`Error fetching bookings: ${err.message}`);
console.error("Error fetching bookings:", err);
}
};
const getUserIdAndFetchBookings = async () => {
const userId = await fetchUserId();
if (userId) {
await fetchBookings(userId);
}
};
getUserIdAndFetchBookings();
}, []);
i just want to fetch booking data when userid from securestore that match with the tenant_id of the booking schema and the the approval field ='accepted'
Solomon Dawit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.