$geonear需要2d或2dsphere索引,但在node.js+monodb中找不到此问题的getdata api

lsmd5eda  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(372)

调用getdata()api时,显示错误: "$geoNear requires a 2d or 2dsphere index, but none were found" 有人这样说: db.collection.createIndex( { <location field> : "2dsphere" } ) 但我不知道我想把这一行,所以请帮助我在节点新
下面是我的模式和getdataapi
postschema.js

var schema = new Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'users'
  },
  price: {
    type: Number
  },
  details: {
    type: String
  },
  location: {
    type: {
      type: String,
      default: "Point"
    },
    coordinates: [Number]
  }
}, {
  collection: 'posts',
  toObject: {
    virtuals: true
  },
  toJSON: {
    virtuals: true
  },
  versionKey: false
})

schema.indexes({ location: '2dsphere' })

getdataapi

getAllPosts: async (req, res) => {
        try {

            let filterQuery = {
                userId: { $ne: req.user._id },
            }

            let aggregateQuery = [];
            aggregateQuery.push({
                $geoNear: {
                    near: { type: "Point", coordinates: req.user.location.coordinates },
                    distanceField: "distanceFrom",
                    spherical: true,
                    query: filterQuery,
                    distanceMultiplier: 0.001
                }
            })

            let posts = await Post.aggregate(aggregateQuery);

            return res.status(200).json({
                success: true,
                message: 'Posts get successfully',
                data: posts
            })
        } catch (err) {
            return res.status(400).json({
                success: false,
                message: err && err.message ? err.message : 'Something went wrong',
                data: {}
            })
        }
    }
wsewodh2

wsewodh21#

你能试着换一个新的吗 indexes 具有 index 在模式定义中

var schema = new Schema({
  ...
  location: {
    type: {
      type: String,
      default: "Point"
    },
    coordinates: [Number]
  }
  ...
)

schema.index({ location: '2dsphere' })

查看有关创建索引的详细信息

相关问题