2015-12-15 89 views
2

我想根據他的位置找到最接近的工人,他們有特定的技能。。其中()由填充字段

位置模式:

var schema = Schema({ 
    name: String, 
    type: String, // home | latest 
    user: {type: Schema.Types.ObjectId, ref: 'User'}, 
    address: String, 
    position: { 
     type: {type: String, default: 'Point'}, 
     coordinates: [Number] 
    }, 
    status: String // active | inactive 
}, {collection: 'locations'}); 

工人模式:

var schema = Schema({ 
    username: String, 
    password: String, 
    firstName: {type: String, default: ''}, 
    middleName: {type: String, default: ''}, 
    lastName: {type: String, default: ''}, 
    role: {type: String, default: 'user'}, // admin | user | worker 
    skills: [{ 
     object: {type: Schema.Types.ObjectId, ref: 'Skill'}, 
     slug: String, // Should remove in the future 
     ratePerHour: Number, 
     status: {type: String, default: 'active'} // active | inactive 
    }], 
    locations: [{type: Schema.Types.ObjectId, ref: 'Location'}] 
}, {collection: 'users'}); 

技能模式:

var schema = Schema({ 
    name: String, 
    slug: String, 
    users: [{type: Schema.Types.ObjectId, ref: 'User'}], 
    isFeatured: Boolean, 
    minRatePerHour: Number, 
    maxRatePerHour: Number, 
    status: String // active | inactive | deleted 
}, {collection: 'skills'}); 

貝婁是我的查詢,但.where()不能與人口領域的工作。

Location 
    .find({ 
     'position': { 
      $near: { 
       $geometry: {type: 'Point', coordinates: [lat, lng]}, 
       $minDistance: 0, 
       $maxDistance: 20000 
      } 
     } 
    }) 
    .populate('user') 
    .deepPopulate('user.skills.object') 
    .where({'user.skills': {$elemMatch: {'object.slug': 'cleaning'}}}) 
    .limit(5) 
    .exec(callback); 

我對這些模式做錯了嗎?我應該使用嵌入式文檔而不是ID參考? 有沒有其他方法可以查詢?

回答

0

你有如下的描述使用特殊屬性populateQuery conditions and other options

所以我認爲你可以像這樣的東西給你結果:

Location 
.find({ 
    'position': { 
    $near: { 
     $geometry: { 
     type: 'Point', 
     coordinates: [lat, lng] 
     }, 
     $minDistance: 0, 
     $maxDistance: 20000 
    } 
    } 
}) 
.populate({ 
    path: 'user', 
    match: { 
    'skills': { 
     $elemMatch: { 
     'object.slug': 'cleaning' 
     } 
    } 
    }, 
    options: { 
    limit: 5 
    } 
}) 
.deepPopulate('user.skills.object') 
.exec(callback); 

沒有測試過,把它僅僅作爲例子。

+0

'object.slug'只存在於'.deepPopulate()'...之後,'object'字段包含'Skill._id'的值 – Manhhailua

+0

這只是一個例子,您應該查看並根據需要修復它。 –

+0

我在'.populate()'中嘗試過'match'選項多次,但它隻影響將被填充的對象。如果用戶在填充期間不匹配,則'用戶'字段將爲'空'。 – Manhhailua