Anurag
Anurag

Reputation: 83

How to store in correct geoJSON format

I am trying to store some data in geoJSON format as follows.

var newUser = {
            'username': $('#addUser fieldset input#inputUserName').val(),
            'location': {type: "Point", coordinates: [ $('#addUser fieldset input#inputUserLocationLng').val(), $('#addUser fieldset input#inputUserLocationLat').val()]},
            'email': $('#addUser fieldset input#inputUserEmail').val(),
            'phone': $('#addUser fieldset input#inputUserPhone').val(),
            'chat': $('#addUser fieldset select#inputChatAllowed').val()                     
        }

And it is saved as shown below.

{
    "_id" : ObjectId("5e327c7b8c0181090e15d445"),
    "username" : "test2",
    "location[type]" : "Point",
    "location[coordinates][]" : [
        77.641145,
        12.89149
    ],
    "email" : "[email protected]",
    "phone" : "8998778987",
    "chat" : "0"
}

But I want the location part in correct geoJSON Format as validated here and shown below.

"location": { 
        "type" : "Point", 
        "coordinates" : [
            -73.856077, 
            40.848447
        ]
    }

I am using mongoose and nodejs. Any suggestions will be helpful.

Also, can a geoJSON data document in mongoDB contain non-location data (name, contact) too?

Upvotes: 1

Views: 106

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59557

The document looks strange. Perhaps this would be a workaround:

doc = db.col.insertOne({
   "username": "test2",
   "email": "[email protected]",
   "phone": "8998778987",
   "chat": "0"
})

db.col.updateOne(
   { _id: doc.insertedId },
   { $set: { "location.type": "Point" } }
)

db.col.updateOne(
   { _id: doc.insertedId },
   { $push: { "location.coordinates": { $each: [-73.856077, 40.848447] } } }
)

or

db.col.updateOne(
   { _id: doc.insertedId },
   {
      $set: {
         "location": {
            type: "Point",
            coordinates: [-73.856077, 40.848447]
         }
      }
   }
)

or

db.col.updateOne(
   { _id: doc.insertedId },
   { $push: { "location.coordinates": -73.856077 } }
)

db.col.updateOne(
   { _id: doc.insertedId },
   { $push: { "location.coordinates": 40.848447 } }
)

Result:

{ 
    "_id" : ObjectId("5e32eb3405a39c3341179e7f"), 
    "username" : "test2", 
    "email" : "[email protected]", 
    "phone" : "8998778987", 
    "chat" : "0", 
    "location" : {
        "type" : "Point", 
        "coordinates" : [
            -73.856077, 
            40.848447
        ]
    }
}

Upvotes: 1

Related Questions