Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose & float values

My lat & lng numbers are being converted to strings. My section integers are still the correct data type of Number. How do I set up model so that I can get my lat & lng back out as Float rather than String?

I'm storing latLng data in my db. Right now I have my data type set to Number for lat & lng. When I check out my db I see this:

{
  "_id" : ObjectId("563bd98a105249f325bb8a7e"),
  "lat" : 41.8126189999999980,
  "lng" : -87.8187850000000054,
  "created" : ISODate("2015-11-05T22:34:50.511Z"),
  "__v" : 0,
  "section" : 0,
}

But when I get my data back out using express I get this:

{
  "_id": "563bd98a105249f325bb8a7e",
  "lat" : "41.8126189999999980",
  "lng" : "-87.8187850000000054",
  "__v": 0,
  "section" : 0,
  "created" : "2015-11-05T22:34:50.511Z",
}

My model:

var WaypointSchema = new Schema({
    lat: {
        type: Number
    },
    lng: {
        type: Number
    },
    section: {
        type: Number
    }
    created: {
        type: Date,
        default: Date.now

    }
});

mongoose.model('Waypoint', WaypointSchema);

Express controller:

exports.list = function(req, res) { 
    Waypoint.find().sort('-created').populate('user', 'displayName').exec(function(err, waypoints) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.jsonp(waypoints);
        }
    });
};
like image 596
Justin Young Avatar asked Nov 06 '15 01:11

Justin Young


2 Answers

While the mongoDB fully supports float type, the mongoose supports only type of Number which is integer. If you try to save to mongoDB float number using mongooses type of Number it will be converted to string.

To sort this out, you will need to load some plugin for mongoose which will extend its value types. There are some plugins which work best with currencies or dates, but in your case I would use https://www.npmjs.com/package/mongoose-double.

Your model after changes would look something like this:

var mongoose = require('mongoose')
require('mongoose-double')(mongoose);

var SchemaTypes = mongoose.Schema.Types;
var WaypointSchema = new Schema({
    lat: {
        type: SchemaTypes.Double
    },
    lng: {
        type: SchemaTypes.Double
    },
    section: {
        type: Number
    }
    created: {
        type: Date,
        default: Date.now
    }
});

mongoose.model('Waypoint', WaypointSchema);

Hope it helps.

like image 185
99problems Avatar answered Oct 16 '22 07:10

99problems


As of the current version of mongoose (v5.12.6), It supports Decimal128 which can be used for this.

like image 2
hack3r-0m Avatar answered Oct 16 '22 06:10

hack3r-0m