如何在 Node.js / Mongoose 中将 Decimal128 值转换为 Float 值?

问题描述 投票:0回答:1

当我使用 Orders.find() 从 MongoDB 数据库查找一些文档时,我从 Node.js 后端服务器获得以下输出。

{
    _id: new ObjectId('6672a038a102620d14a93cac'),
    userId: 6458,
    orderId: 106733,
    orderAmount: new Decimal128('134.25'),
    orderStatus: 100,
    orderDate: 2024-06-19T09:09:12.246Z,
    processed: false,
    __v: 0
  },

订单架构如下:

const OrderSchema = new mongoose.Schema({
  userId: {
    type: Number,
  },
  orderId: {
    type: Number,
  },
  orderAmount: {
    type: mongoose.Types.Decimal128,
  },
  orderStatus: {
    type: Number,
  },
  orderDate: {
    type: Date,
    default: Date.now,
  },
  processed: {
    type: Boolean,
    default: false,
  },
  
});

感谢您将 orderAmount 从 Decimal128 转换为浮点数的宝贵帮助。

我的预期输出是:

{
    _id: new ObjectId('6672a038a102620d14a93cac'),
    userId: 6458,
    orderId: 106733,
    orderAmount: 134.25,
    orderStatus: 100,
    orderDate: 2024-06-19T09:09:12.246Z,
    processed: false,
    __v: 0
  },
javascript node.js mongodb mongoose mongoose-schema
1个回答
0
投票

这是一个解决方案,其中使用聚合而不是 find() 在数据库端完成转换

db.collection.aggregate([
  {
    $match: {
      // filter necessary like find()
    }
  },
  {
    $set: {
      orderAmount: {
        $toDouble: "$orderAmount"
      }
    }
  }
])

游乐场

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.