如何在 Rest 上转换 Decimal128 值 [英] How to translate Decimal128 values over Rest

查看:71
本文介绍了如何在 Rest 上转换 Decimal128 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Mongoose 作为包的一部分,节省了大量时间.

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

我使用的包是https://github.com/florianholzapfel/express-restify-猫鼬.当我查询 Mongodb 并且我有一个 Decimal128 类型时,它返回这样的值:

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"
    }
}

当它在 Mongoose 对象中时很好,但是当我通过 Rest API 公开它时(这个包使用 restify),它只是一个 json 表示.

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.

如果我在 Patch 或 Put 请求中通过 REST Api 将其发回 - 就像字符串或数字(见下文)一样,它可以正常工作并将其存储在数据库中,并使用 Mongoose 模型正确翻译它.

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"
}

如何在 MongoDb 中将其存储为十进制类型,但通过 REST 将其公开为数字?我只是不知道该怎么做.

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.

我猜可能发生的 3 个方面是

The 3 areas it could happen I guess are

  1. 猫鼬模型
  2. 重新调整
  3. 猫鼬中的某种钩子".

我对两者都不太熟悉.感谢您抽出宝贵时间.

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

推荐答案

以下作品:

function getFloat(value) {
  return value && value['$numberDecimal'] ? value['$numberDecimal'] : 0;
}

使用示例:

getFloat(obj1.buyPrice)

这篇关于如何在 Rest 上转换 Decimal128 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆