Search code examples
javascriptnode.jsmongoose2dsphere

2dSphere query showing error unknown operator


Im using 2d Sphere to find user data from cosmosDB using mongoose But i keep getting error `unknown operator: $nearSphere

const userSchemaModel = new mongoose.Schema(
    {
        contactNumber: {
            type: String,
        },
        name: String,
        
        loc: {
            type: {
                type: String,
                default: "Point",
            },
            coordinates: {
                type: [Number],
                default: [0, 0],
            },
        },
        
    },
    { timestamps: true }
);

userSchemaModel.index({ loc: "2dsphere" });

this is the model in the model, i have defined the loc with a type of point and coordinates as given in the documentation

for this model I'm trying to get the query

currentUser = await User.findById(userId),
            
const userLocation = currentUser.loc.coordinates;

User.find({
    "loc.coordinates": {
            $nearSphere: {
                $geometry: { type: "Point", coordinates: userLocation },
                $minDistance: 0,
                $maxDistance: 10 * 1000,
               },
            }
    })

also tried this

User.find({
    loc: {
            $nearSphere: {
                $geometry: { type: "Point", coordinates: userLocation },
                $minDistance: 0,
                $maxDistance: 10 * 1000,
               },
            }
    })

but i keep getting this error

MongoServerError: unknown operator: $nearSphere
    at Connection.onMessage (C:\Users\shiva\Documents\GitHub\umla\umla-user-service\node_modules\mongodb\lib\cmap\connection.js:202:26)
    at MessageStream.<anonymous> (C:\Users\shiva\Documents\GitHub\umla\umla-user-service\node_modules\mongodb\lib\cmap\connection.js:61:60)
    at MessageStream.emit (node:events:514:28)
    at processIncomingData (C:\Users\shiva\Documents\GitHub\umla\umla-user-service\node_modules\mongodb\lib\cmap\message_stream.js:124:16)
    at MessageStream._write (C:\Users\shiva\Documents\GitHub\umla\umla-user-service\node_modules\mongodb\lib\cmap\message_stream.js:33:9)
    at writeOrBuffer (node:internal/streams/writable:447:12)
    at _write (node:internal/streams/writable:389:10)
    at Writable.write (node:internal/streams/writable:393:10)
    at TLSSocket.ondata (node:internal/streams/readable:817:22)
    at TLSSocket.emit (node:events:514:28) {
  ok: 0,
  code: 2,
  codeName: 'BadValue',
  [Symbol(errorLabels)]: Set(0) {}
}

Solution

  • There are 2 types of cosmos DB in assure on RU and V-cores, RU has been there for a long time and supports spatial query, but on the other hand, v-core is relatively new and it still doesn't support spatial query, and many more features