I am creating a node application that use cosmosDB with mongodb API. The application will allows users to perform tasks on other resources based on roles assigned.
// Users Schema
const userSchema = mongoose.Schema({
email: String,
password: String
});
// Hotel Schema
const hotelSchema = mongoose.Schema({
name: String,
people: {
type: [{
userId: {
type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true
},
role: {
type: String, ref: 'User', enum: ['Visitor', 'Worker']
}
}]
}
});
The hotel can have a list of people which is an array containing the user and their role. I want to be able to query the hotel using the userId and retrieve only the array element from 'people' that contains the matching userId.
I have tried:
Hotel.find({
'people.userId': request.params.id
},
{
people: {
$elemMatch: {
userId: request.params.id
}
}
},
{ 'people.$': 1 });
I expected the result to be:
[
{
'name': 'Hotel 1',
'people': [
{
'email': 'bob@some.com',
'role': 'Worker',
'_id': '59c3f09b8146bd11dce0fd42'
}
]
}
]
But what I end up getting is:
[
{
'name': 'Hotel 1',
'people': [
{
'email': 'bob@some.com',
'role': 'Worker',
'_id': '59c3f09b8146bd11dce0fd42'
},
{
'email': 'peter@some.com',
'role': 'Worker2',
'_id': '59c3f1f48146bd11dce0fd54'
},
{
'email': 'john@some.com',
'role': 'Visitor',
'_id': '59c3f1f48146bd11dce0fd56'
}
]
}
]
Is there a way to achieve my expected result without having to extract the element from the results in javascript code.
Thanks