我已经在SO
上检查了这个场景的其他答案,但不幸的是,它们似乎都不适合我。
我正在使用以下依赖项:
" Mongoose "一九九七年十一月五日
- typescript **:第四章第七节第四节
我有一个transactions
集合,其中包含trxValue
属性,该属性的值采用decimal
。我遇到了Mongoose
中引入的新Decimal128
类型,并尝试通过以下方式实现相同的类型:
// ITransaction.ts interface file
import { Types } from 'mongoose';
export default interface ITransaction {
trxNo: string;
trxType: 'Credit' | 'Debit';
trxDate: Date;
trxDesc: string;
trxValue: string;
cutomerId: Types.ObjectId;
accountId: Types.ObjectId;
}
// Transactions.ts model file
import { model, Schema } from 'mongoose';
import ITransaction from '../interfaces/ITransaction';
const trxSchema = new Schema<ITransaction>({
trxNo: { type: String, required: true },
trxType: { type: String, required: true },
trxDate: { type: Date, default: Date.now },
trxDesc: { type: String, required: true },
trxValue: {
type: Schema.Types.Decimal128,
required: true,
get: (v: Schema.Types.Decimal128): string => (+v.toString()).toFixed(4),
},
cutomerId: { type: Schema.Types.ObjectId, required: true },
accountId: { type: Schema.Types.ObjectId, required: true },
});
const Transaction = model<ITransaction>('Transaction', trxSchema);
export default Transaction;
问题是数据类型Decimal128
似乎与typescript原语数据类型不匹配。我在编译时一直收到以下警告。有人能给我一个详细的例子吗?如何在MongoDB
中使用Mongoose
+ Typescript
和小数点后**4位数的precision
来存储和获取十进制值?
Type '{ type: typeof Schema.Types.Decimal128; required: true; get: (v: Schema.Types.Decimal128) => string; }' is not assignable to type 'SchemaDefinitionProperty<string> | undefined'.
Types of property 'type' are incompatible.
Type 'typeof Decimal128' is not assignable to type 'typeof Mixed | StringSchemaDefinition | undefined'.
Type 'typeof Decimal128' is not assignable to type 'typeof Mixed'.
Types of property 'schemaName' are incompatible.
Type '"Decimal128"' is not assignable to type '"Mixed"'.ts(2322)
2条答案
按热度按时间jk9hmnmh1#
变通方案
zxlwwiss2#
似乎适合我的配置如下所示:
Demo