1

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
  },
5
  • 1
    You can just apply the unary + to it, like +orderAmount, and you'll get a native JavaScript number type. Be aware that there can be loss of precision. Commented Jun 20, 2024 at 10:21
  • 2
    mongoplayground.net/p/2tFTFeyth-i not sure if there are better ways Commented Jun 20, 2024 at 10:30
  • @cmgchess, That was an awesome solution. It worked very well, Thank you! I believe you can put the same as a working solution so that I can mark it as a solution Commented Jun 20, 2024 at 11:35
  • @trincot, I didnot understand where and how should I apply the unary + operator... if possible, please explain it a bit more Commented Jun 20, 2024 at 11:42
  • 1
    maybe he meant like if you have the result (say something like const res = await db.findOne....) then const decimalValue = +res.orderAmount or if it returns multiple docs might have to .map through it and then convert Commented Jun 20, 2024 at 12:08

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @cmgchess. Even if I had to modify my code to use aggregate() instead of find() , the issue is solved in the backend itself and the frontend is safe to use the API without any special handling for displaying the orderAmount field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.