Extract Decimal from Decimal128 with Mongoose - MongoDB

前端 未结 3 1088
被撕碎了的回忆
被撕碎了的回忆 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: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());
    

提交回复
热议问题