If I have the following collection:
{
"restaurant": {
"_id": "5c0711f23533ef13a3e53d8b",
"name": "burger king",
"description": "american",
"reservations": [
{
"_id": "5c0712503533ef13a3e53d8c",
"time": "1:00 pm",
"people": 3
},
{
"_id": "5c0717129a8d7213e46d92da",
"time": "9:30 am",
"people": 10
},
{
"_id": "5c071960160f2a13f647e100",
"time": "12:30 am",
"people": 25
}
],
"__v": 0
}
}
and if I want to POST return only a specific reservation with restaurant's _id, name, description, like:
{
"restaurant": {
"_id": "5c0711f23533ef13a3e53d8b",
"name": "burger king",
"description": "american",
"reservations": [
{
"_id": "5c0717129a8d7213e46d92da",
"time": "9:30 am",
"people": 10
}
],
"__v": 0
}
}
What would be the best way?
I tried:
Restaurant.find( {_id: ObjectID(id)}, {reservations : { $elemMatch: {time: time} }, {$elemMatch: {people: people}} } )
.then( (restaurant)=> {
res.send({restaurant})
})
but not working. Any help would be appreciated
Your query is incorrect .
The match should look like this:
Restaurant.find( {_id: ObjectID(id)}, {
name: 1,
description: 1,
reservations : { $elemMatch: {time: time, people: people} } } )
.then( (restaurant)=> {
res.send({restaurant})
})
And make sure _id is actually of type ObjectID and not of type String
The following query works fine(testing locally):
db.getCollection('test').find({_id: '5c0711f23533ef13a3e53d8b'}, {name:1, description: 1, reservations: {$elemMatch: {people: 3, time: '1:00 pm'}}})
Please notice that I'm using string _id and not object id.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.