[英]How to select parent based on children's value using mongoose and GraphQL?
我正在尝试实现与条件 JOIN 查询等效的功能,但随后使用 GraphQL。 我使用 Mongoose 作为我的数据库模型和 MongoDB 作为数据库。
我将用以下 graphQL 模式说明我的问题:
type Booking {
_id: ID!
client: Client!
rooms: Room!
activities: Activity!
nrOfAdults: Int!
arrivalDate: String!
departureDate: String!
}
type Room {
_id: ID!
name: String!
contents: String
priceNight: Float!
maxAdults: Int!
reservations: [Booking]
}
猫鼬模式:
const bookingSchema = new Schema(
{
client: {
type: Schema.Types.ObjectId,
ref: 'Client'
},
rooms: [{
type: Schema.Types.ObjectId,
ref: 'Rooms'
}],
nrOfAdults: {
type: Number,
required: true
},
arrivalDate: {
type: Date,
required: true
},
departureDate: {
type: Date,
required: true
}
},
{ timestamps: true }
);
const roomSchema = new Schema({
name: {
type: String,
required: true
},
priceNight: {
type: Number,
required: true
},
maxAdults: {
type: Number,
required: true
},
reservations: [
{
type: Schema.Types.ObjectId,
ref: 'Booking'
}
]
});
我可以查询房间,例如,如果我想为我运行的 3 个或更多成人获取房间:
Room.find({
maxAdults: { $gte: 3 }
});
这工作正常。
但是,我还想显示可用房间,这意味着我需要对保留在预订中的预订对象强加条件。 我认为这会很容易,使用类似的东西:
Room.find({
maxAdults: { $gte: 3 },
reservations: { $elemMatch: { arrivalDate: { $gte: *some date*}}}
});
但它返回一个空数组,而它应该返回一些值,基于 mongodb 中的数据:
为了让事情更清楚一点,我想获得与以下 SQL 查询相同的结果:
SELECT *
FROM room
JOIN booking ON room.id = booking.roomId
WHERE
room.maxAdults >= 3
AND
(
booking.arrivalDate > CAST('2020-05-15' AS DATE)
OR
booking.departureDare < CAST(2020-05-06' AS DATE)
)
假设您保存的值与您在 mongoose 模式中提到的值类似。
探索如何在 mongodb 中加入。 目的是在对来自不同集合的子字段执行查询之前进行连接。
相关答案: 如何在 MongoDB 中执行等效的 SQL Join?
我建议使用聚合管道来完成你想要的。
建议代码:
Room.aggregate([
{
$match: {
maxAdults: { $gte: 3 }
}
},
{
$lookup: {
from: "bookings",
localField: "reservations",
foreignField: "_id",
as: "booking"
}
},
{
$unwind: '$booking'
},
{
$match: {
booking.arrivalDate: { $gte: *some date* }
}
},
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.