Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose-mongoDB advanced query joins

I have two models in my database, the Room model and Block model

The room schema

var RoomSchema = new Schema({
  name: String,
  floor: { type: Number, min: 0},
  capacity: { type: Number, min: 0},
  free: { type: Number, min: 0},
  block: {type: mongoose.Schema.Types.ObjectId, ref: 'Block'}
});

the block schema

var BlockSchema = new Schema({
  name: String,
  type: Boolean, // 0->man, 1->woman
  rooms: [{type: mongoose.Schema.Types.ObjectId, ref: 'Room'}]
});

I would like to retrieve all rooms that belong to a block where the type is false (rooms for men), so if I was to write this in pseduo sql it would be like

select * from rooms
left join blocks on blocks.id = romms.block_id
where blocks.type = false;  

filtering the rooms entities just after the query returns, won't work because it would change the pagination data.

Any help is appreciated!!

like image 723
benaich Avatar asked Feb 09 '23 11:02

benaich


1 Answers

This has to be done as two separate queries in mongodb as it is not a relational database.

First do the blocks query:

db.blocksCollection.find({type : false})

This will return an array of blocks of type false.

This can be used to query the rooms collection for rooms in those blocks, using the $in operator: http://docs.mongodb.org/manual/reference/operator/query/in/

db.roomsCollection.find({block : { $in : [block1,block2,etc...]}})
like image 194
Carasel Avatar answered Feb 12 '23 10:02

Carasel