【问题标题】:Mongoose : Can't populate after find to make $near queryMongoose:find 后无法填充以进行 $near 查询
【发布时间】:2018-08-23 02:49:54
【问题描述】:

我正在尝试填充用户信息以获取他的位置,但我得到了undefined。 这是我的架构:

AnnounceSchema:

const AnnounceSchema = new mongoose.Schema({
  titre: String,
  contenu: String,
  image: String,
  tag: String,
  media: String,
  date: {
    type: Date,
    default: Date.now
  },
  commentaires: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
  authorId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
})

用户架构:

const UserSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  loc: { type: { type: String, default: 'Point' }, coordinates: { type: [Number] } }
});
UserSchema.index({ loc: '2dsphere' });

这是我的查询:

Announce.find({})
  .populate('authorId', null,
    {
      'authorId.loc': {
        $near: {
          $geometry: {
            type: 'Point',
            coordinates: [req.user.loc.coordinates[0], req.user.loc.coordinates[1]]
          },
          $maxDistance: 10000
        }
      }
    })
  .exec((err, announces) => {
    if (err) {
      res.send(err)
    } else {
      res.render('announce/search', { announces: announces })
    }
  })

我得到的错误是"unable to find index for $geoNear query"。我已向 AnnonceSchema 添加了索引,但没有更改:

AnnonceSchema.index({ "authorId.loc" : "2dsphere"})

【问题讨论】:

    标签: node.js mongodb mongoose populate


    【解决方案1】:

    这应该可行:

    Announce.find({})
      .populate('author',
        {
          path : 'authorId',
          match: {
            'loc': {
              $near: {
                $geometry: {
                  type: 'Point',
                  coordinates: [req.user.loc.coordinates[0], req.user.loc.coordinates[1]]
                },
                $maxDistance: 10000
              }
            }
          },
          model: 'User',
        })
      .exec((err, announces) => {
        if (err) {
          res.send(err)
        } else {
          res.render('announce/search', { announces: announces })
        }
      })
    

    populate 有两种工作方式

    • 它可以通过引用填充Announce.find({}).populate('authorId')
    • 或通过自定义查询(这是您需要的)

    【讨论】:

    • 它有效@m1ch4ls !谢谢!我正在努力解决docs
    • 请注意,我必须输入 .populate({path : 'authorId', match : { 'loc' : { ......}}}) 以避免出现 Unsupported projection 错误
    猜你喜欢
    • 1970-01-01
    • 2015-09-11
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 2012-07-03
    相关资源
    最近更新 更多