首页 > 解决方案 > Nest JS / MongoDB - 地理空间索引在部署的服务器上不起作用

问题描述

我正在用 NestJS 编写一个 API,它获取存储在 MongoDB 数据库中的数据并使用 GraphQL 来返回它。Devices它应该使用一个名为location- GeoJSON 点的属性来获取。上面还有一个2dsphere索引,它允许Devices使用查询在一个圆圈中$geoNear搜索。在本地机器上一切正常,但是当 API 部署在服务器上时Devices,尽管存在记录和索引,但循环查询不会返回任何记录。

搜索查询如下所示:

  const location = [input.center.lng, input.center.lat]

  return [
    {
      $geoNear: {
        near: {
          type: 'Point',
          coordinates: location
        },
        distanceField: 'distance',
        maxDistance: input.radius,
        key: 'location'
      }
    }
  ]

DevicesService 使用此管道:

该数据库是使用 Kubernetes 部署的。这是配置:

apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.22.0 (955b78124)
  creationTimestamp: null
  labels:
    io.kompose.service: v3-ds-mongo
  name: v3-ds-mongo
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: v3-ds-mongo
  strategy:
    type: Recreate
  template:
    metadata:
      annotations:
        kompose.cmd: kompose convert
        kompose.version: 1.22.0 (955b78124)
      creationTimestamp: null
      labels:
        io.kompose.service: v3-ds-mongo
    spec:
      containers:
        - env:
            - name: MONGO_INITDB_ROOT_PASSWORD
              value: password
            - name: MONGO_INITDB_ROOT_USERNAME
              value: root
          image: mongo:latest
          name: v3-ds-mongo
          ports:
            - containerPort: 27017
          resources: {}
          volumeMounts:
            - mountPath: /data/db
              name: v3-ds-mongo-claim0
      restartPolicy: Always
      volumes:
        - name: v3-ds-mongo-claim0
          persistentVolumeClaim:
            claimName: v3-ds-mongo-claim0
status: {}

提前谢谢你的帮助。

标签: mongodbgraphqlnestjs

解决方案


索引也应该在服务器上创建,您可以手动执行此操作但效率不高,但是您可以为数据库创建一个初始化文件来定义索引:

connection = new Mongo();

db = connection.getDB("database_name")

db.users.createIndex({ location: '2dsphere' })

并在您的配置中引用该文件


推荐阅读