The system has encountered a MongoDB error stating: 'Unable to retrieve geographical keys from object' specifically with Type: Point

Trying to set up my database field for geocoding like this:

MyCollection._ensureIndex({'data.address.located':'2dsphere'});

However, encountering an error message:

MongoError: Can't extract geo keys from object, malformed geometry?:
{ type: "Point", coordinates: [ 32.4586858, -110.8571443 ] }

Having trouble identifying the issue with this field. Any suggestions?

Referencing this link, it provides this example:

The following example stores a GeoJSON Point:

{ loc: { type: "Point", coordinates: [ 40, 5 ] } }

Answer №1

It seems that there is an issue with the given coordinates

[ 32.4586858, -110.8571443 ]

as they do not follow the correct format for longitude and latitude. The order should be longitude first followed by latitude, but in this case it appears to be reversed (since the valid latitude range is -90 to 90 and -110.8571443 falls outside of that).

Perhaps you intended:

{ type: "Point", coordinates: [ -110.8571443, 32.4586858 ] }

or there may have been another input error.

Answer №2

As highlighted by the user @go-oleg, the issue lies in the specified range of coordinates:

  • Longitude: (+-) 180°
  • Latitude: (+-) 90°

The index expects the coordinates to fall within these boundaries.

If you are trying to utilize the index on data that has already been imported and discover that the coordinates are switched, it would be more efficient to simply swap them back instead of reimporting the entire collection. The following mongoshell script can help with this:

Assuming you have a properly formatted GeoJSON object of type Point.

db.coll.find().forEach(function (e) {
    // assuming `geoJson` field contains `coordinates`
    e.geoJson.coordinates = [ // Swapping Lat/Lon
        e.geoJson.coordinates[1], // Longitude comes first
        e.geoJson.coordinates[0] // Latitude comes last
    ];
    db.coll.save(e);
    // Optionally, include a `print(e.name)` statement here to track progress
});

Answer №3

While I had the correct longitude and latitude order, I encountered a problem. The issue was that I had written coordiantes instead of coordinates, causing MongoDB to show this error:

pymongo.errors.WriteError: Can't extract geo keys: {data}  Point must be an array or object

It's possible that you have the right ordering but there may be an issue with your key names.

Answer №4

Although the issue has been resolved, it's worth noting that this bug could resurface if the type of GeoJSON object is omitted.

In my situation, I was able to fix it by including type: 'Point' in the model's value.

Answer №5

I encountered a similar error, but the root cause was having a LineString with two identical coordinates.

"geometry" : {
    "type" : "LineString",
    "coordinates" : [ 
        [ 
            143.345763, 
            -33.840952
        ], 
        [ 
            143.345763, 
            -33.840952
        ]
    ]
}

To resolve this issue, I had to convert it into a Point for it to be considered valid.

"geometry" : {
    "type" : "Point",
    "coordinates" : [ 
        143.345763, 
        -33.840952
    ]
}

Answer №6

Start by inserting data in the correct object format to avoid errors.

schema :
location:{
            type: { type: String },
            coordinates:[mongoose.Schema.Types.Mixed]
        },

Then, proceed with inserting data into the database.

db.userDetails.createIndex({location: "2dsphere"})

An index will only be created if the location field contains an object.

Next, write a query to find the distance.

db.userDetails.aggregate( [
 $geoNear: {
                  near: { type: "Point",  coordinates: [data.lat1,data.lon1]},
                  spherical: true,
                  "distanceMultiplier" : 0.001,
                  distanceField: "calcDistance",
                  $maxDistance: distance,

               }
] )

Lastly, make sure to pass data without using quoted strings like this:

"lat":18.7323
"lon":73.1232 

This is important for proper data handling.

Answer №7

One issue I encountered was that the coordinates were initially stored as strings rather than integers or floats.

To resolve this, I made the following adjustment:

{ type: "Point", coordinates: [ "9.27261834568901", "55.9298104971287" ] } }

Modified to:

{ type: "Point", coordinates: [ 9.27261834568901, 55.9298104971287 ] } }

Using:

const new_lat = parseFloat(old_lat)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve the JavaScript variable name for a rhandsontable displayed in a Shiny application?

My project involves using the rhandsontable package to generate dynamic tables within a Shiny app. I am in need of a solution that allows me to select certain cells programmatically, triggered by specific user interactions. Unfortunately, I have not been ...

Bootstrap / Blazor - no action when clicking on an image link

Having issues with adding a simple HTML link around an image in my Bootstrap 4.5 / Blazor app. When I click on the link, nothing happens. How is this possible? I've tried using the <a href"..."><img ...> pattern, as well as NavL ...

Oops, there was an issue while trying to delete the user with ID "delete8" on the local server. Access was

I have implemented Sweetalert in CakePHP 4, but I am facing an issue where the data is not getting deleted after confirming the deletion. Below are the relevant code snippets: File: template/layout/Users/index.php <table> <tr> <th>Us ...

Taking you back to the main page

I've encountered a problem with my Vue registration where clicking on the register button redirects me to the home page. I believe setting some conditions might help resolve this issue. How can I prevent this redirection? Any suggestions? register() { ...

What is the best way to conceal the second and fourth rows of a table using either css or jquery?

I have a piece of code that is dynamic and I need to hide the second and fourth 'tr' elements of the table with the id HMP_options. How can I accomplish this? <table id="HMP_options" width="100%" cellspacing="0" cellpadding="0" border="0"> ...

An effective approach to retrieving the results of a query by leveraging the observer pattern

I am a newcomer to the Scala world and I am seeking help with my project. I am currently working on a Scala application that saves files to a MongoDB database using the official MongoDB Scala driver. I previously used Casbah, but since it is classified as ...

What is the best way to alter the href of menu items while excluding 2 specific items

I've successfully updated the href attribute of my menu items using jQuery based on the website address: if(window.location.href.indexOf("en") > -1) { var link = $('#main-nav a'); link.each(function(){ this.href += ' ...

Unveil the socket connection using web sockets

My current setup involves a server generating a socket on port 8181. I am interested in accessing this socket from a web page viewed in Google Chrome version 14. It seems that direct access may not be feasible, as Chrome only supports Web Sockets and not s ...

Deleting object properties in JavaScript is not possible

obj = {a: []} I need to remove the element obj.a. The following code does the job: if(!obj.a.length) delete obj.a // it works However, the below code does not achieve the desired result: function _delete(o) { if(!o.length) delete o } _d ...

Tips on utilizing CSS modules in React without changing class names

After starting to use css modules in my react project, I quickly realized the struggle of changing classnames to fit the requirements of css modules. For example, if we have a component using regular css: import React from 'react' import ". ...

What causes a ReferenceError when attempting to retrieve the class name of a React component?

Take a look at my React component located in index.js: import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { render() { return ( <div className="App"> <h1>Hello, ...

Node.js Express causing JSON object formatting issue with MongoDB insertion

Currently, I am creating JSON objects that have this structure: var newSong = { 'name': 'Song', 'genre': 'Genre', 'percent': '100', 'lyrics': [ ...

Sending a piece of state information to a different component

Hey, I'm a new React developer and I'm struggling with a particular issue. I've included only the relevant code snippets from my app. Basically, I want to retrieve the data from the clicked Datagrid row, send it to a Dialog form, and then p ...

Generate an array that can be accessed across all components

As someone new to reactjs, I'm trying to figure out how to handle an array of objects so that it can be global and accessed from multiple components. Should I create another class and import it for this purpose? In Angular, I would typically create a ...

Here is a unique rewrite of the text:"Implementing a feature to upload an image in PHP and AJAX without

Although it may seem repetitive, I have yet to find a solution that perfectly fits my requirements. I am looking to upload an image to a designated folder by simply selecting a file in the file browser, without the use of a submit button (which I have acco ...

Utilize MongoDB provider to efficiently sort through numerous parameters

Below is a schema for a document I have: { "name":"Name", "region":"New Jersey", "address":"92 Something Rd", "city":"Jersey City", "state":"NJ", "zipCode":"07302", "country":"USA", amenities":[ "Sa ...

magnetic container: stationary container nested within absolutely positioned container

I recently created a page that can be viewed here: [LINK] This page is set up to scroll horizontally, resulting in a row of divs with black borders. However, I am facing an issue with the smaller divs inside (red ones). I want them to stay within the par ...

When JSON data is copied and displayed in Node.js or JavaScript, it appears as a string

I have written a code to copy one JSON file into another JSON file. Here is the code: function userData(){ fs.copyFile( path.join(process.cwd(), "user/access.json"), path.join(process.cwd(), "client/access.json"), ...

Determine the frequency of duplicate elements in an array and arrange them in descending order based on their frequency

After making an API call, my array is populated with values like this: ["9777", "9777", "2.4", "9777", "2.4", "2.4", "9777", "2.4", "2.4", "9777", "9777", "2.4", "2.4", "2.4"] My goal is to count the occurrences of each item in the array and then sort th ...

Error message: Next.js - Unable to access properties of an undefined object (user)

I am currently utilizing Next.js and Next-auth in my current project. Within this project, I am working on creating a Sidebar component that will display a list of items specific to each user. To achieve this, I am using the useSession hook to retrieve t ...