【问题标题】:.where() by populated fields.where() 通过填充字段
【发布时间】:2016-03-20 20:03:14
【问题描述】:

我想根据他的位置找到最近的具有特定技能的工人。

位置架构:

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 参考吗? 有没有其他方法可以查询?

【问题讨论】:

    标签: mongodb mongoose mongoose-populate


    【解决方案1】:

    您必须使用populate 的特殊属性,如下所述:Query 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);
    

    未测试,仅作为示例。

    【讨论】:

    • object.slug 仅存在于.deepPopulate() ... 之后,object 字段包含Skill._id 的值
    • 这只是一个示例,您应该根据自己的需要查看和修复它。
    • 我在.populate() 中尝试了几次match 选项,但它只影响将被填充的对象。如果用户在填充期间不匹配,user 字段将为 null
    猜你喜欢
    • 2015-11-21
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2021-04-01
    • 2018-10-01
    • 2017-07-21
    • 1970-01-01
    相关资源
    最近更新 更多