我正在尝试在mongodb中存储双BSON类型。我在用猫鼬。我尝试了所有可能的方法,但仍将其存储为int。 我已经尝试过@ mongoosejs / double和mongoose-float,但是它们都不起作用。
await Variant.insertOne(
{
price: 345,
discount: 10,
},
)
产品型号
import { Schema } from "mongoose"
const Double = require("@mongoosejs/double")
// const Float = require("mongoose-float").loadType(mongoose)
export const ProductVariantEmbeddedSchema = new Schema({
price: Double,
discount: Double,
})
这是我在@ mongoosejs / double的帮助下创建的自定义类型。
import mongoose from "mongoose"
export default function mongooseDouble(mongoose) {
class DoubleType extends Number {
constructor(v) {
super(v)
this.value = v
}
toBSON() {
return this.value
}
}
class Double extends mongoose.SchemaType {
constructor(key, options) {
super(key, options, "Double")
Object.assign(this.$conditionalHandlers, {
$lt: (val) => this.castForQuery(val),
$lte: (val) => this.castForQuery(val),
$gt: (val) => this.castForQuery(val),
$gte: (val) => this.castForQuery(val),
})
}
cast(val) {
if (val == null) {
return val
}
const _val = Number(val)
if (isNaN(_val)) {
throw new mongoose.SchemaType.CastError(
"Double",
val + " is not a valid double"
)
}
return new DoubleType(_val)
}
}
mongoose.Schema.Types.Double = Double
mongoose.Types.Double = DoubleType
return mongoose
}
//导出默认的Double
答案 0 :(得分:1)
我相信没有Double
这样的类型。 JavaScript具有Number
,它支持int,float,double等。此外,如果您看到猫鼬的文档,那么您会看到Double
不是有效的类型。相反,您应该使用Number
。
const ProductVariantEmbeddedSchema = new Schema({
price: Number,
discount: Number,
});
编辑:在评论中进行讨论后,我相信这可以解决。
const price = 5;
await Model.create({
price: price * 1.0001,
...
});
在数据库中,价格将为双精度类型,但值将为5.0005
。因此,每当要使用price
的值时,请将其设置为int
或使用.toFixed(2)
或类似函数将小数点限制为2位。
答案 1 :(得分:0)
好吧,如果猫鼬自定义类型不起作用,我可以使用原始mongodb查询。
import mongoose, {mongo} from 'mongoose'
const result = await mongoose.connection.collection('Variant').insertMany([{price: new mongo.Double(34)}, {price: new mongo.Double(45)}])
const storedValues = result.opt