0

I have 2 models in Next.js app, Booking and User. Obj bellow is booking obj. When User booked some dates, new obj in booking is created. When user open booking details page, should see details of booking. I have a problem to select a specific object that belongs to the user. I was trying this, and it shows me all objects:

 _id: ObjectId(64b8440c8ff8e8950641fd7e)  // id of boooking obj
user: ObjectId(64b4cd15d0ef7c21d80ecd4d)  // id of user

in front end

const { user } = useSelector((state) => state.userAuth)
const userID = user?.user?._id

than I am using this userID to find specific obj

const res = await axios.post('/api/bookingDetails/bookDetails', userID, config ) 
// config is headers: {"Content-Type": "application/json"}

and in backend this code

const id = req.body.userID

const user = await Booking.find( id )
res.status(200).json({ 
     message: 'success ',
     user
    })
Peret
  • 79
  • 8

1 Answers1

1
To select a specific booking object that belongs to a user in Next.js, you need to modify your code in the front-end and back-end as follows:

Front-end code:

import { useSelector } from 'react-redux';

const { user } = useSelector((state) => state.userAuth);
const userID = user?.user?._id;

const res = await axios.post('/api/bookingDetails/bookDetails', { userID }, config);
// Pass userID as an object and include it in the request body
```

Backend code:

const id = req.body.userID;

const bookings = await Booking.find({ user: id });
// Find bookings where the user field matches the provided user ID

res.status(200).json({ 
    message: 'success',
    bookings
});
```

In the front-end, make sure to pass the `userID` as an object with the key `userID` in the request body. This allows you to access it in the back-end as `req.body.userID`.

In the back-end, use `await Booking.find({ user: id })` to find all bookings where the `user` field matches the provided user ID. This will return an array of bookings that belong to the user. You can then send this array of bookings (`bookings`) in the response.

Please ensure that the `user` field in the `Booking` model corresponds to the user ID stored in `userID`. Adjust the field name if necessary.

By making these changes, you should be able to select and display the specific booking objects belonging to the user on your booking details page.