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

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

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

  1. var schema = new Schema({
  2. userId: {
  3. type: mongoose.Schema.Types.ObjectId,
  4. ref: 'users'
  5. },
  6. price: {
  7. type: Number
  8. },
  9. details: {
  10. type: String
  11. },
  12. location: {
  13. type: {
  14. type: String,
  15. default: "Point"
  16. },
  17. coordinates: [Number]
  18. }
  19. }, {
  20. collection: 'posts',
  21. toObject: {
  22. virtuals: true
  23. },
  24. toJSON: {
  25. virtuals: true
  26. },
  27. versionKey: false
  28. })
  29. schema.indexes({ location: '2dsphere' })

getdataapi

  1. getAllPosts: async (req, res) => {
  2. try {
  3. let filterQuery = {
  4. userId: { $ne: req.user._id },
  5. }
  6. let aggregateQuery = [];
  7. aggregateQuery.push({
  8. $geoNear: {
  9. near: { type: "Point", coordinates: req.user.location.coordinates },
  10. distanceField: "distanceFrom",
  11. spherical: true,
  12. query: filterQuery,
  13. distanceMultiplier: 0.001
  14. }
  15. })
  16. let posts = await Post.aggregate(aggregateQuery);
  17. return res.status(200).json({
  18. success: true,
  19. message: 'Posts get successfully',
  20. data: posts
  21. })
  22. } catch (err) {
  23. return res.status(400).json({
  24. success: false,
  25. message: err && err.message ? err.message : 'Something went wrong',
  26. data: {}
  27. })
  28. }
  29. }
wsewodh2

wsewodh21#

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

  1. var schema = new Schema({
  2. ...
  3. location: {
  4. type: {
  5. type: String,
  6. default: "Point"
  7. },
  8. coordinates: [Number]
  9. }
  10. ...
  11. )
  12. schema.index({ location: '2dsphere' })

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

相关问题