在猫鼬模式中使用 getter 格式化数据时出现差异
Discrepancies while formatting data using getter in a mongoose schema
我正在尝试使用 get
关键字四舍五入 Account
模型架构的平衡,同时使用 mongoose 从 MongoDB 检索数据。
当我使用 accounts[0].balance
显式检查余额值时,它确实给出了四舍五入的数字。
但是,帐户对象中的余额 属性 仍显示为十进制数。我在下面粘贴了控制台的输出结果。
我想知道为什么值存在差异,以及是否可以修复它以便我 return 的对象自动具有四舍五入的平衡。
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 }
]
来自余额属性: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,
);
我正在尝试使用 get
关键字四舍五入 Account
模型架构的平衡,同时使用 mongoose 从 MongoDB 检索数据。
当我使用 accounts[0].balance
显式检查余额值时,它确实给出了四舍五入的数字。
但是,帐户对象中的余额 属性 仍显示为十进制数。我在下面粘贴了控制台的输出结果。
我想知道为什么值存在差异,以及是否可以修复它以便我 return 的对象自动具有四舍五入的平衡。
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 }
]
来自余额属性: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,
);