gpt4 book ai didi

javascript - 在 Mongoose 模式中使用 getter 格式化数据时出现差异

转载 作者:行者123 更新时间:2023-12-02 23:19:43 26 4
gpt4 key购买 nike

我试图在使用 mongoose 从 MongoDB 检索数据时使用 get 关键字舍入 Account 模型架构的平衡。当我使用accounts[0].balance显式检查余额值时,它确实给出了四舍五入的数字。但是,帐户对象中的余额属性仍然显示小数。我把控制台的输出结果贴在下面。我想知道为什么值存在差异,以及是否可以修复它,以便我返回的对象将自动具有舍入平衡。

    const Account = mongoose.model(
"Balances",
new mongoose.Schema({
name: { type: String, required: true, minlength: 3, maxlength: 50 },
balance: { type: Number, get: p => Math.round(p) }
})
);

router.get("/", async (req, res) => {
const accounts = await Account.find().sort("name");
console.log("From accounts object: ", accounts);
console.log("From balance propery: ", accounts[0].balance);
res.send(accounts);
});

`From accounts object: [
{ _id: 5d27df2d9e553ec4d48ae7f6,
name: 'savings',
balance: 234.8 }
]

来自余额属性(property):235`

最佳答案

您必须使用以下语法启用 Mongoose getter 函数:

schema.set('toObject', { getters: true });
schema.set('toJSON', { getters: true });

在您的情况下,代码将出现:

const AccountSchema = new mongoose.Schema({
name: { type: String, required: true, minlength: 3, maxlength: 50 },
balance: { type: Number, get: p => Math.round(p) }
});

AccountSchema.set('toObject', { getters: true });
AccountSchema.set('toJSON', { getters: true });

const Account = mongoose.model(
"Balances",
AccountSchema,
);

关于javascript - 在 Mongoose 模式中使用 getter 格式化数据时出现差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56999615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com