假设我们在MongoDB中有此文档。
{
"hotel": "5cd02fe495be1a4f48150447",
"calendar": [
{
"_id": "5cd17ede23d621471d88ec20",
"date": "1970-01-01T00:00:00.001Z",
"rooms": [
{
"_id": "5cd17ede23d621471d88ec22",
"room": "5cd17d82ca56fe43e24ae5d3",
"price": "",
"remaining": 0,
"reserved": 0
},
{
"_id": "5cd17ede23d621471d88ec21",
"room": "5cd17db6ca56fe43e24ae5d4",
"price": "",
"remaining": 0,
"reserved": 0
}
]
},
]
}
我需要在与req.body.id匹配的房间中选择一个内部数组,并更新该对象。 这是身体部位:
{
"id": "5cd17ede23d621471d88ec22",
hotelId: "5cd02fe495be1a4f48150447",
price: "10000",
}
这是架构:
const calendarSchema = mongoose.Schema({
hotel: {
type: mongoose.Schema.ObjectId,
ref: "Hotel",
required: true
},
calendar: [
{
date: Date,
rooms: [
{
room: {
type: mongoose.Schema.ObjectId,
ref: "Room",
required: true
},
price: {
type: String
},
remaining: {
type: Number
},
reserved: {
type: Number
}
}
]
}
]
});
module.exports = mongoose.model("Calendar", calendarSchema);
挑战在于如何在房间中选择内部对象。 这是我的查询: db.calendars.find({hotel:ObjectId(“ 5cd02fe495be1a4f48150447”),“ calendar.rooms”:{$ elemMatch:{_ id:ObjectId(“ 5cd17ede23d621471d88ebd7”)}},)