How to translate Decimal128 values over Rest
Asked Answered
D

1

0

I'm using Mongoose as part of a package , saving heaps of time.

The package I am using is https://github.com/florianholzapfel/express-restify-mongoose. When I query Mongodb , and I have a Decimal128 type , it returns those values like this:

{
    "sku": "shGHYB12-60-LOZ",
    "name": "Prd",
    "size": "60",
    "buyPrice": {
        "$numberDecimal": "12.55"
    }
}

Which is fine when it's in a Mongoose object , but when I expose it over the Rest API ( this package uses restify ) , it is just a json representation.

If I post it back through the REST Api in a Patch or Put request - just as a string or number ( see below ) , it works fine and stores it in the database correctly translating it using the Mongoose model.

{
    "sku": "shGHYB12-60-LOZ",
    "name": "Prd",
    "size": "60",
    "buyPrice": "12.5995"
}

The Part of my mongoose model is like this

"buyPrice": {
    "type": "Decimal"
}

How can I store it as a decimal type in MongoDb but expose it as a number over REST? I'm just not sure how to go about it.

The 3 areas it could happen I guess are

  1. The Mongoose model
  2. Restify
  3. Some sort of "hook" in Mongoose.

I'm not overly familiar with either. Thanks for your time.

Demythologize answered 11/7, 2018 at 11:38 Comment(5)
You could massage the data structure a little bit before you send it out (maybe in the controller or better yet by creating a model wrapper function). Use parseFloat("1.23") to turn the string representation into a float.Undercast
@Undercast the whole point of Decimal128 is to avoid the float type.Demythologize
A float is a decimal. Your question might need some clarification.Undercast
@Undercast I hope these will help you understand the difference. net-informations.com/q/faq/float.html , api.mongodb.com/python/3.4.0/api/bson/decimal128.html . This is why I am referring to Decimal128 , which solves the rounding issues with the float type. If you have something that will help me then please post an answer , otherwise please just let it rest! Thanks.Demythologize
@MartinThompson were you able to figure it out? All the answers I got are converting back to Float and not Decimal128.Skid
S
0

Make a helper function before declaring a schema:

   function getMoney(value) {
      if (typeof value !== 'undefined') {
         return parseFloat(value.toString());
      }
      return value;
    }

Add a getter to your field like this:

price: {
      type: Schema.Types.Decimal128,
      get: getMoney
    },
Schizogony answered 26/2, 2019 at 11:7 Comment(1)
I also though of the same idea, but this doesn't seem to work for meMayers

© 2022 - 2024 — McMap. All rights reserved.