使用Mongoose从Decimal128中提取小数-MongoDB

时间:2018-11-19 06:56:35

标签: javascript node.js mongodb mongoose

我正在用Mongoose在Nodejs中查询Mongo,并尝试提取存储为Decimal128的多个字段的数值。但是,该值奇怪地包装在查询结果中,我不确定如何通过Mongo或Mongoose提取它:

{data:[
  {
  "date": {
          "$numberDecimal": "1530057600000"
  },
  "open": {
          "$numberDecimal": "86.13"
  },
  "high": {
          "$numberDecimal": "86.63"
  },
  "low": {
          "$numberDecimal": "85.47"
  },
  "close": {
          "$numberDecimal": "85.64"
  },
  "volume": {
          "$numberDecimal": "308508"
  }
},

有没有一种方法可以使用Mongo或Mongoose将上面的JSON查询结果转换为下面的内容?

{data:[
 {
  "date": 1530057600000
  "open": 86.13
  "high": 86.63
  "low": 85.47
  "close": 85.64
  "volume": 308508
 },

我尝试如下选择字段,但这没有用。

    data[i].date.$numberDecimal, 
    data[i].open.$numberDecimal,
    data[i].high.$numberDecimal,
    data[i].low.$numberDecimal, 
    data[i].close.$numberDecimal 

这是我的猫鼬模式:

文件夹-模型-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)

控制器

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

我正在将数据发送到前端,这就是我在浏览器中收到的内容:

enter image description here

解决方案

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

3 个答案:

答案 0 :(得分:2)

方法1:

使用 toString()。它将对象转换为字符串。

function foo(one: string, two: number): string {}

输出如下:-

function foo(one, two) {}

方法2: 以上的Mongodb 4.0,

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

答案 1 :(得分:0)

工作解决方案

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

答案 2 :(得分:0)

这将适用于任何字段!

它也支持子文档和子文档数组

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

用法:

MyModel.findOne().then(data => console.log(data.toJSON());