Search code examples
mongodbbson

How can I specify BSON type for coordinates when inserting in MongoDb?


I have the following document, on which I want to create a 2dsphere index, but the coordinates field must be an integer BSON type in order to do that. However the data type which comes from the client comes in as a string for the coordinates.

So I would like to change that to integer before inserting into the MongoDb so that I can create the index afterwards. How can I do that?

user.saveSubscriber = (jSubscriberData, fCallback) => {
    var jSubscriber = {
        email: jSubscriberData.txtEmail,
        firstName: jSubscriberData.txtName,
        lastName: jSubscriberData.txtLastName,
        address: {
            type: "Point",
            coordinates: [jSubscriberData.lng, jSubscriberData.lat]
        }
    }
    global.db.collection('subscribers').insertOne(jSubscriber, (err, jResult) => {

        if (err) {
            var jError = { "status": "error", "message": "ERROR -> saveSubscriber -> user.js -> 001" }
            return fCallback(false, jError)
        }
        var jOk = { "status": "ok", "message": "user.js ->  subscriber saved -> 000" }
        return fCallback(false, jOk)
    })
}

Solution

  • Just Parse the string to float before storing by using parseFloat()

    user.saveSubscriber = (jSubscriberData, fCallback) => {
    var jSubscriber = {
        email: jSubscriberData.txtEmail,
        firstName: jSubscriberData.txtName,
        lastName: jSubscriberData.txtLastName,
        address: {
            type: "Point",
            coordinates: [parseFloat(jSubscriberData.lng), parseFloat (jSubscriberData.lat)]
        }
    }
    global.db.collection('subscribers').insertOne(jSubscriber, (err, jResult) => {
    
        if (err) {
            var jError = { "status": "error", "message": "ERROR -> saveSubscriber -> user.js -> 001" }
            return fCallback(false, jError)
        }
        var jOk = { "status": "ok", "message": "user.js ->  subscriber saved -> 000" }
        return fCallback(false, jOk)
    })
    

    }