如何在Node.js中获取所有匹配数据?我只得到部分数据

发布于 2025-02-03 23:08:44 字数 4475 浏览 2 评论 0原文

我正在node.js中构建公共汽车票预订应用程序。运行GET查询后,我只收到有关公共汽车而不是座位的数据,而是我也想要座位数据。

有许多不同的桌子,例如公交桌,位置桌,路线桌,预订台以及许多其他桌子。

在此总线表中,管理员可以输入有关总线数字和总座位等总线的数据。之后,在位置和路由表中,只有管理员可以输入数据,下面是路由架构:

const routeSchema = new mongoose.Schema(
  {
    Location: {
      from: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Location",
        required: true,
      },
      to: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Location",
        required: true,
      },
    },
    busId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Bus",
      required: true,
    },
    date: {
      type: String,
      required: true,
    },
);

从和引用到同一位置表存储了两个不同的集合。

之后,授权用户可以通过提供必要的详细信息来选择路线,公共汽车和座位来预订门票。这是预订表模式:

const bookingSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  routeId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Route",
    required: true,
  },
  passengers: [
    {
      name: { type: String, required: true, trim: true },
      gender: { type: String, required: true, trim: true },
      age: { type: Number, required: true, trim: true },
    }],
  phone: {
    type: Number,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  bookingDate: {
    type: String,
    required: true,
  },
  fare: {
    type: Number,
    required: true,
  },
  seats: {
    type: [Number],
    required: true,
  },
  departureDetails: [
    {
      city: { type: String, required: true, trim: true },
      location: { type: String, required: true, trim: true },
      time: { type: String, required: true, trim: true },
      date: { type: String, required: true, trim: true },
    },
  ],
  arrivalDetails: [
    {
      city: { type: String, required: true, trim: true },
      location: { type: String, required: true, trim: true },
      time: { type: String, required: true, trim: true },
      date: { type: String, required: true, trim: true },
    },
  ],
},{
    timestamps:true
});

但是现在,问题开始在我想向我的应用程序的每个用户展示将在该路线和可用座位上运行的公交车的每个用户都开始,并保留在该路线上的每一个总线中。预订座位存储在预订表中。

我的总线数据正确正确,但座位数据未显示。它正在返回一个空阵列

,这里是获取公共汽车和座位数据的Get请求:

router.get("/trip/single", async (req, res) => {
  if (!req.query.from || !req.query.to || !req.query.date) {
    return res.send({
      error: "Please enter the data to get the trip",
    });
  }
  const { from, to, date } = req.query;

  const routes = await Route.find({
    "Location.from": from,
    "Location.to": to,
     "date": date.toString(),
  });

  const matchedBus = await routes.filter(() =>{
    return Route.busId === routes._id
  });

  const bookings = await Booking.find({
    routeId: { $in: matchedBus.map((matchedBus) => matchedBus._id)  },
  });
  const busIdWithSeatsObj = {};
  
  for (let i = 0; i < matchedBus.length; i++) {
    let currentBusSeats = [];
    var busData = matchedBus.map(data => data)
    console.log(busData);
    **// Every thing is working fine till here. busData is returning the data as shown below**

    const busBookings = bookings.filter((booking) => {
      return (
        **//something is wrong here but I can not figure out what is wrong**
        booking.date === date.toString() &&
        booking.busId === matchedBus[i]._id
      );
    });
    console.log(busBookings);
       **//here busBookings is returning an empty array which is a big problem.**
    busBookings.forEach(() => {
      currentBusSeats = [...currentBusSeats, ...Booking.seats];
    });
    busIdWithSeatsObj[matchedBus[i]._id] = currentBusSeats;
  }

  res.status(200).send({ routes, matchedBus, busIdWithSeatsObj });
});

Busdata的控制台日志是:

[
  {
    Location: {
      from: new ObjectId("6295f0986f9e32990d8b3488"),
      to: new ObjectId("6295f0c06f9e32990d8b348b")
    },
    _id: new ObjectId("6295f12c6f9e32990d8b348e"),
    busId: new ObjectId("6295f0836f9e32990d8b3485"),
    date: '2022-06-02',
    departureTime: 11,
    arrivalTime: 6.3,
    createdAt: 2022-05-31T10:42:52.785Z,
    updatedAt: 2022-05-31T10:42:52.785Z,
    __v: 0
  }
]

我通过这样的查询:127.0.0.0.1:3000/trip/trip/single?from=6295f095986F9E3299E3299990D8B3488&ampamp ; to = 6295F0C06F9E32990D8B348B&amp; date = 2022-06-02

现在,我正在比较我猜在不起作用的for for for for for for for的日期和busid。我该怎么做才能使它起作用并获取匹配的数据?

谁能在这里帮我吗?

I am building a bus ticket booking app in node.js. After running the GET query I am getting only data about Buses not the seats but I want seats data as well.

There are many different tables like bus-table, locations-table, route-table, booking-table and many other as well.

In this bus table an admin can enter the data about Bus like bus number and total seats. After that in the location and route table only admin can enter the data and below is the route schema:

const routeSchema = new mongoose.Schema(
  {
    Location: {
      from: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Location",
        required: true,
      },
      to: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Location",
        required: true,
      },
    },
    busId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Bus",
      required: true,
    },
    date: {
      type: String,
      required: true,
    },
);

Both from and to are referenced to same location table where two different collections are stored.

After that an authorized user can book tickets by selecting the route, bus and seats by providing necessary details. Here is the booking table schema:

const bookingSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  routeId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Route",
    required: true,
  },
  passengers: [
    {
      name: { type: String, required: true, trim: true },
      gender: { type: String, required: true, trim: true },
      age: { type: Number, required: true, trim: true },
    }],
  phone: {
    type: Number,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  bookingDate: {
    type: String,
    required: true,
  },
  fare: {
    type: Number,
    required: true,
  },
  seats: {
    type: [Number],
    required: true,
  },
  departureDetails: [
    {
      city: { type: String, required: true, trim: true },
      location: { type: String, required: true, trim: true },
      time: { type: String, required: true, trim: true },
      date: { type: String, required: true, trim: true },
    },
  ],
  arrivalDetails: [
    {
      city: { type: String, required: true, trim: true },
      location: { type: String, required: true, trim: true },
      time: { type: String, required: true, trim: true },
      date: { type: String, required: true, trim: true },
    },
  ],
},{
    timestamps:true
});

But now the problem starts here in the GET request where I want to show every user of my app about the buses which will run on that route and seats available and reserved in every single bus running on that route. Booked seats are stored in the Booking table.

I am getting the bus data right and correctly but seats data is not showing. It is returning an empty array

Here is the GET request to get the bus and seats data:

router.get("/trip/single", async (req, res) => {
  if (!req.query.from || !req.query.to || !req.query.date) {
    return res.send({
      error: "Please enter the data to get the trip",
    });
  }
  const { from, to, date } = req.query;

  const routes = await Route.find({
    "Location.from": from,
    "Location.to": to,
     "date": date.toString(),
  });

  const matchedBus = await routes.filter(() =>{
    return Route.busId === routes._id
  });

  const bookings = await Booking.find({
    routeId: { $in: matchedBus.map((matchedBus) => matchedBus._id)  },
  });
  const busIdWithSeatsObj = {};
  
  for (let i = 0; i < matchedBus.length; i++) {
    let currentBusSeats = [];
    var busData = matchedBus.map(data => data)
    console.log(busData);
    **// Every thing is working fine till here. busData is returning the data as shown below**

    const busBookings = bookings.filter((booking) => {
      return (
        **//something is wrong here but I can not figure out what is wrong**
        booking.date === date.toString() &&
        booking.busId === matchedBus[i]._id
      );
    });
    console.log(busBookings);
       **//here busBookings is returning an empty array which is a big problem.**
    busBookings.forEach(() => {
      currentBusSeats = [...currentBusSeats, ...Booking.seats];
    });
    busIdWithSeatsObj[matchedBus[i]._id] = currentBusSeats;
  }

  res.status(200).send({ routes, matchedBus, busIdWithSeatsObj });
});

The console log of busData is:

[
  {
    Location: {
      from: new ObjectId("6295f0986f9e32990d8b3488"),
      to: new ObjectId("6295f0c06f9e32990d8b348b")
    },
    _id: new ObjectId("6295f12c6f9e32990d8b348e"),
    busId: new ObjectId("6295f0836f9e32990d8b3485"),
    date: '2022-06-02',
    departureTime: 11,
    arrivalTime: 6.3,
    createdAt: 2022-05-31T10:42:52.785Z,
    updatedAt: 2022-05-31T10:42:52.785Z,
    __v: 0
  }
]

I am passing the query like this:127.0.0.1:3000/trip/single?from=6295f0986f9e32990d8b3488&to=6295f0c06f9e32990d8b348b&date=2022-06-02

Now I am comparing the date and busId in the for loop which is not working I guess. What should I do to make it work and get the matched data?

Can anyone help me out here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没企图 2025-02-10 23:08:44
const filterCondition = 
[
  {
    '$match': {
      'Location.from': ObjectId('6295f0986f9e32990d8b3488'), // import ObjectId from mongoose package
      'Location.to': ObjectId('6295f0c06f9e32990d8b348b'), 
      'date': '2022-06-02'
    }
  }, {
    '$lookup': {
      'from': 'Booking', 
      'localField': 'busId', 
      'foreignField': 'routeId', 
      'as': 'bookings'
    }
  }, 
  {'$unwind': '$bookings'} // remove this if you want bookings to be in array.
];

const data = await Route.aggregate(filterCondition);

可以使用下面的操场并检查响应是否。
https://mongoplayground.net.net/p/p/3bhsk28x8og

const filterCondition = 
[
  {
    '$match': {
      'Location.from': ObjectId('6295f0986f9e32990d8b3488'), // import ObjectId from mongoose package
      'Location.to': ObjectId('6295f0c06f9e32990d8b348b'), 
      'date': '2022-06-02'
    }
  }, {
    '$lookup': {
      'from': 'Booking', 
      'localField': 'busId', 
      'foreignField': 'routeId', 
      'as': 'bookings'
    }
  }, 
  {'$unwind': '$bookings'} // remove this if you want bookings to be in array.
];

const data = await Route.aggregate(filterCondition);

Can use the below playground and check if the response.
https://mongoplayground.net/p/3BHsK28X8OG

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文