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

Bellow 是我的查询,但.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 参考吗?有没有其他方法可以查询?

4

1 回答 1

0

您必须使用populate此处描述的特殊属性:查询条件和其他选项

因此,我认为您可以通过以下方式获得结果:

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

未经测试,仅作为示例。

于 2015-12-15T08:20:10.230 回答