Extract Decimal from Decimal128 with Mongoose - MongoDB

前端 未结 3 1053
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 13:25

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 que

相关标签:
3条回答
  • 2021-01-19 14:02

    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"},
        }},
    ]);
    
    0 讨论(0)
  • 2021-01-19 14:16

    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());
    
    0 讨论(0)
  • 2021-01-19 14:19

    Working 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)
        })
    }
    
    0 讨论(0)
提交回复
热议问题