2

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

kajan
  • 132
  • 1
  • 9
  • Where is the user_id in people array ? After you resolve this use `Hotel.find({ 'people.userId': request.params.id }, { 'people.$': 1 });` – s7vr Sep 21 '17 at 18:46
  • What do you mean by user_id? userId that I use in my query is from the user object. As it holds an array of objects which in turn has a reference to user and a field for the role. – kajan Sep 21 '17 at 19:21
  • Turns out that $elemMatch is not implemented in the mongodb api port for cosmosdb – kajan Sep 26 '17 at 14:39

0 Answers0