2016-06-29 68 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对象。