I'm querying Mongo in Nodejs with Mongoose and attempting to extract the numeric value of multiple fields stored as a Decimal128. However, the value is oddly wrapped in query results and I'm not sure how to extract it through Mongo or Mongoose:
{data:[
{
"date": {
"$numberDecimal": "1530057600000"
},
"open": {
"$numberDecimal": "86.13"
},
"high": {
"$numberDecimal": "86.63"
},
"low": {
"$numberDecimal": "85.47"
},
"close": {
"$numberDecimal": "85.64"
},
"volume": {
"$numberDecimal": "308508"
}
},
Is there a way I can use Mongo or Mongoose to convert the above JSON query-result into what's below?
{data:[
{
"date": 1530057600000
"open": 86.13
"high": 86.63
"low": 85.47
"close": 85.64
"volume": 308508
},
I tried selecting the fields as follows ,but this didn't work.
data[i].date.$numberDecimal,
data[i].open.$numberDecimal,
data[i].high.$numberDecimal,
data[i].low.$numberDecimal,
data[i].close.$numberDecimal
Here's my Mongoose schema:
Folder - Model - Stock.js
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
const childSchemaData = new mongoose.Schema({
"_id": false,
date: {type: mongoose.Types.Decimal128},
open: {type: mongoose.Types.Decimal128},
high: {type: mongoose.Types.Decimal128},
low: {type: mongoose.Types.Decimal128},
close: {type: mongoose.Types.Decimal128},
volume: {type: mongoose.Types.Decimal128}
})
const parentSchemaSymbol = new mongoose.Schema({
"_id": false,
symbol: {
type: String,
trim: true,
minlength: 2,
maxlength: 4,
uppercase: true,
required: 'Plese enter a valid symbol, min 2 characters and max 4'
},
// Array of subdocuments
data: [childSchemaData],
slug: String
})
module.exports = mongoose.model('Stock', parentSchemaSymbol)
Controller
const mongoose = require('mongoose')
const parentSchemaSymbol = mongoose.model('Stock')
exports.dbFetch = (req, res) => {
let curValueDbFetch = req.params.symbol
const query = { symbol: `${curValueDbFetch}` }
const projection = { _id: 0, data: 1 }
parentSchemaSymbol.findOne(query, projection).then(doc => {
return res.send(doc)
}).catch(e => {
console.log(e)
})
}
I am sending the data to the front end and this is what I am receiving in the browser:
SOLUTION
const mongoose = require('mongoose')
const parentSchemaSymbol = mongoose.model('Stock')
exports.dbFetch = (req, res) => {
let curValueDbFetch = req.params.symbol
const query = { symbol: `${curValueDbFetch}` }
const projection = { _id: 0, data: 1 }
parentSchemaSymbol.findOne(query, projection).sort({ date: -1 }).then(doc => {
let chartData = doc.data.map(item => {
return {
date: parseFloat(item.date), // the date
open: parseFloat(item.open), // open
high: parseFloat(item.high), // high
low: parseFloat(item.low), // low
close: parseFloat(item.close), // close
volume: parseFloat(item.volume)// volume
}
})
res.send(chartData)
})
.catch(e => {
console.log(e)
})
}
Method 1: .
use toString(). It will convert the object to string.
find((docs) => {
let result = docs.map((doc) => {
if(doc.open){
doc.open = doc.open.toString();
}
if(doc.close){
doc.close = doc.close.toString();
}
return doc;
});
//send modified output
res.json(result);
})
output as follows:-
/*
[
{
"open": "86.13",
"close": "85.64"
},
]
*/
Method 2: Mongodb 4.0 above,
db.myCollection.aggregate([
{$match:{
//...
//...
}},
{ $addFields : {
open: {"$toString" : "$open"},
close : {"$toString" : "$close"},
}},
]);
This will work with any field!
It supports subdocument and arrays of subdocuments too
const MySchema = new Schema({/*... schema fields ...*/});
const decimal2JSON = (v, i, prev) => {
if (v !== null && typeof v === 'object') {
if (v.constructor.name === 'Decimal128')
prev[i] = v.toString();
else
Object.entries(v).forEach(([key, value]) => decimal2JSON(value, key, prev ? prev[i] : v));
}
};
MySchema.set('toJSON', {
transform: (doc, ret) => {
decimal2JSON(ret);
return ret;
}
});
mongoose.model('MyModel', MySchema);
Usage:
MyModel.findOne().then(data => console.log(data.toJSON());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With