2016-06-29 69 views
-2

我有以下模式:MongoDB的多參數,搜索查詢

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 
} 
); 

應用背景是一樣的Airbnb/Roomi的應用程序,用戶可以給的租金他們的房間/場所。現在我想爲用戶找到適當的房間列表實現一個過濾器。

這裏creatorId,rules,amneties是其他模式的refIds。我想寫一個查詢,它會根據幾個參數 用戶可以在請求查詢中傳遞規則,定價信息,部分小工具,性別等信息。 查詢參數取決於用戶的意願。 有沒有什麼辦法像這樣做事情的嵌套查詢?就像我們在SQL中所做的那樣。

回答

0

那麼,mongodb不會被用作關係數據庫。

相反,我會建議將amenities amenities中的amenities數組轉換爲一個對象數組,並將其中的設施嵌入到Listings模式中。

這樣你就可以查詢如下:

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

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

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

有MongoDB中都沒有加入,你仍然可以做「加入」貓鼬稱它們填充,但它們發生在服務器上,每個人羣需要往返服務器。

如果您仍然希望使用對amneties集合的引用,則應先查詢它並在其上填充Listing對象。