aliyun-mdb-floatfix

1.0.3 • Public • Published

阿里云函数nodejs-mongodb,存储浮点数兼容函数

在云函数中将浮点数存储到mongodb时,数据库会自动转为对象的bug (num字段应该为浮点数类型):

{
  "_id": "5f44cdd367f1376654bef7a8",
  "num": {
    "high": 3471712362749231000,
    "low": 15648,
    "negative": false,
    "naN": false,
    "infinite": false,
    "finite": true
  }
}

安装

npm i -s aliyun-mdb-floatfix

使用

方式一: 在获取数据后,进行一次转换

const deepParseFloat = require('aliyun-mdb-floatfix');
 
 
let result = await cloud.db.collection('float').find(
        {  
            _id: '5f44cdd367f1376654bef7a8' 
        }, 
        {  
            limit: 1, 
        }
    )
    
    
    result = deepParseFloat(result) //深度遍历转换对应的对象为浮点数
 

方式二: 统一挂入钩子

云函数端

 
const { hook } = require('aliyun-mdb-floatfix');
 
exports.get = async (context) => {
    const cloud = context.cloud; 
    const openId = context.openId;
 
    hook(cloud);  //挂入钩子 当调用find aggregate函数结果会自动处理浮点数对象
 
    let result = await cloud.db.collection('float').find(
        {  
            _id: '5f44cdd367f1376654bef7a8' 
        }, 
        {  
            limit: 1, 
        }
    )
    return result[0][openId];
};
 

小程序端

import cloud from '@tbmp/mp-cloud-sdk';
import { hook } from 'aliyun-mdb-floatfix';
 
cloud.init({
  env: 'test'
});
 
hook(cloud); //挂入钩子 当调用find aggregate函数结果会自动处理浮点数对象
 
let getData = async ()=>{
  let result = await cloud.db.collection('float').find(
          {  
              _id: '5f44cdd367f1376654bef7a8' 
          }, 
          {  
              limit: 1, 
          }
      )
  console.log(result);
  return result
}
 

Package Sidebar

Install

npm i aliyun-mdb-floatfix

Weekly Downloads

2

Version

1.0.3

License

MIT

Unpacked Size

4.47 kB

Total Files

3

Last publish

Collaborators

  • tangoboy