MongoDB,按用户查找预订对象

问题描述 投票:0回答:1

我在 Next.js 应用程序中有 2 个模型:Booking 和 User。下面的 obj 正在预订 obj。 当用户预订某些日期时,会在预订中创建新的对象。当用户打开预订详细信息页面时,应该看到预订的详细信息。我在选择属于用户的特定对象时遇到问题。我正在尝试这个,它向我显示了所有对象:

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

在前端

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

比我使用这个用户ID来查找特定的对象

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

在后端这段代码

const id = req.body.userID

const user = await Booking.find( id )
res.status(200).json({ 
     message: 'success ',
     user
    })
javascript reactjs mongodb next
1个回答
1
投票

在Next.js中选择属于某个用户的特定预订对象,需要修改前后端代码如下:

前端代码:

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

后端代码:

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
});

在前端,请确保将

userID
作为对象传递,并在请求正文中使用键
userID
。这允许您在后端以
req.body.userID
的形式访问它。

在后端,使用

await Booking.find({ user: id })
查找
user
字段与所提供的用户 ID 匹配的所有预订。这将返回属于用户的一系列预订。然后,您可以在响应中发送这组预订 (
bookings
)。

请确保

user
模型中的
Booking
字段与
userID
中存储的用户ID相对应。如有必要,请调整字段名称。

通过进行这些更改,您应该能够在预订详细信息页面上选择并显示属于该用户的特定预订对象。

© www.soinside.com 2019 - 2024. All rights reserved.