javascriptnode.jsmongodbmongoosemongoose-schema

How to convert Decimal128 value to Float value in Node.js / Mongoose?


I got the following output from the Node.js backend server when I use the Orders.find() to find some documents from the MongoDB database.

{
    _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
  },

The Orders schema is as follows:

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,
  },
  
});

Appreciate your valuable help in converting the orderAmount from Decimal128 to a floating number.

My expected output is:

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

Solution

  • Here is a solution where the conversion is done on DB side using an aggregation instead of a find()

    $toDouble

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

    playground