SyedAliRazaSherazi SyedAliRazaSherazi - 5 months ago 21
Node.js Question

MONGODB MULTI PARAMETER SEARCH QUERY

I have the following schema:

var ListingSchema = new Schema({


creatorId : [{ type: Schema.Types.ObjectId, ref: 'User' }],//LISTING CREATOR i.e. specific user
roommatePreference: { //preferred things in roommate
age: {//age preferences if any
early20s: { type: Boolean, default: true },
late20s: { type: Boolean, default: true },
thirtys: { type: Boolean, default: true },
fortysAndOld: { type: Boolean, default: true }
},
gender: {type:String,default:"Male"}
},

roomInfo: {//your own location of which place to rent
address: {type:String,default:"Default"},
city: {type:String,default:"Default"},
state: {type:String,default:"Default"},
zipcode: {type:Number,default:0},

},

location: {//ROOM LOCATION
type: [Number], // [<longitude>, <latitude>]
index: '2d' // create the geospatial index
},

pricing: {//room pricing information
monthlyRent: {type:Number,default:0},
deposit: {type:Number,default:0},
},

availability:{//room availability information
durationOfLease: {
minDuration: {type:Number,default:0},
maxDuration: {type:Number,default:0},
},
moveInDate: { type: Date, default: Date.now }
},


amneties : [{ type: Schema.Types.ObjectId, ref: 'Amnety' }],


rules : [{ type: Schema.Types.ObjectId, ref: 'Rule' }],

photos : [{ type: Schema.Types.ObjectId, ref: 'Media' }],//Array of photos having photo's ids, photos belong to Media class

description: String,//description of room for roomi

status:{type:Boolean,default:true}//STATUS OF ENTRY, BY DEFAULT ACTIVE=TRUE
},

{
timestamps:true
}
);


The application background is like Airbnb/Roomi app, where users can give their rooms/places on rent. Now i want to implement a filter for a user finding the appropriae listing of room.

Here creatorId, rules, amneties are refIds of other schemas. I want to write a query which will give me listings based on several parameters,
e.g. user can pass rules, pricing info, some amneties, gender etc in req queries.
The query parameters depends upon user's will.
Is there any way to do nested query like thing for this?, like the way we did in SQL.

Answer

Well, mongodb is not made to be used as relational DB.

instead, i would suggest transforming amenities array into an array of objects with the amenities embeded inside the Listings schema.

so you can query as follows:

// Schema
ListSchema = mongoose.Schema({
....
amneties: [{type: 'shower'}]

// or you can make it a simple array of strings:
// amneties: ['shower']
....
})

// query
Listings.find({'amneties.type' : <some amenity>})

there are no joins in mongodb, you can still make "joins" as mongoose calls them populate, but they are happening on your server, and every populations requires a round trip to the server.

if you still wish to use references to the amneties collection, you should query it first and populate the Listing object on them.

Comments