【发布时间】:2020-08-06 09:04:27
【问题描述】:
下面是我的猫鼬模式
const mongoose = require('mongoose');
const AccountingCostsSchema = mongoose.Schema(
{
// other properties goes here
accountCosts: {
type: mongoose.Decimal128,
set: (v) =>
mongoose.Types.Decimal128.fromString(parseFloat(v).toFixed(4)),
required: true
}
},
{
collection: 'accountingCosts'
}
);
export = mongoose.model('AccountingCosts', AccountingCostsSchema);
MongoDB 中的数据
accountingCosts 收集
文本模式视图中的数据
{
"_id" : ObjectId("4e1eb38c2bdea2fb81f5e771"),
"accountId" : ObjectId("4e8c1180d85de1704ce12110"),
"accountCosts" : NumberDecimal("200.00"),
}
文本模式视图中的数据
我的查询
db.getCollection('accountingCosts').find({'accountId': '4e8c1180d85de1704ce12110'})
查询结果
"accountCosts": {
"$numberDecimal": "123.00"
}
我尝试在架构上编写一个 getter 函数,就像我有一个 setter 函数一样。但它不起作用
get: function(value) {
return value.toString();
}
我的预期输出只是一个普通属性,其名称和值如下所示
"accountCosts": "123.00"
【问题讨论】:
-
toString()不起作用。有关解决方案,请参阅 - stackoverflow.com/a/66320724/984471 -
@TheJoker,您是否能够修复它而不像许多答案那样将其转换为浮点数或字符串?我希望它保持为 Decimal128 数字。
标签: node.js mongodb mongoose mongoose-schema