使用Mongoose - MongoDB从Decimal 128中提取小数

kyvafyod  于 2022-11-03  发布在  Go
关注(0)|答案(5)|浏览(338)

我正在用Mongoose查询Nodejs中的Mongo,并试图提取存储为Decimal 128的多个字段的数值。但是,该值奇怪地被 Package 在查询结果中,我不确定如何通过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

下面是我的 Mongoose 模式:

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

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

解决方案

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

0g0grzrc1#

方法1:

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

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

输出如下:-

/*
[
  {
    "open":  "86.13",
    "close": "85.64"
  },
]

* /

**方法2:**Mongodb 4.0以上版本,

db.myCollection.aggregate([
  {$match:{
   //...
   //...
   }},

  { $addFields : {
        open: {"$toString" : "$open"},
        close : {"$toString" : "$close"},
    }},
]);
of1yzvn4

of1yzvn42#

这适用于任何字段!

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

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

mqkwyuun3#

工作溶液

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

ut6juiuv4#

这对于lodash _.cloneDeepWith()来说非常容易。迭代每个对象属性,并将具有$numberDecimal属性的对象转换为字符串。

// first flattenDecimals using mongoose `toJSON()`
var objectStep1= dbResult.toJSON({flattenDecimals: true});
//  use lodash _.cloneDeepWith() to iterate over every object property
var returnThisObject = _.cloneDeepWith(objectStep1, propVal =>{
    if (_.has(propVal, '$numberDecimal')) return propVal.$numberDecimal;
});

或者你也可以在没有toJSON()的情况下这样做,但是我认为这样做效率会比较低,因为mongoose结果有太多的属性不是结果的一部分,然后你还需要检查未定义的属性。

var returnThisObject = _.cloneDeepWith(dbResult, propVal =>{
    if (!propVal) return propVal; // check for undefined 
    if ('Decimal128' == propVal ._bsontype) return propVal.toString();
});
piwo6bdm

piwo6bdm5#

在我的例子中,value undefined即使数据库文档有关键字,因为在模式中我忘记添加该字段,但我试图读取该值。

相关问题