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

标签 javascript mongodb mongoose getter

我试图在使用 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/

相关文章:

node.js - *ngIf-else 不显示 else 结果

javascript - 按钮呈现但未调用回调

javascript - ExtJS 4 在商店中按一列分组,总计另一列

c# - 使用并行写入 MongoDB 时出错

java - 检查网页是否已经下载

ajax - 如何更新EJS模板+AJAX?

javascript - React 类组件异常 this 对方法的绑定(bind)

javascript - 使用javascript解析文件名

javascript - Meteor 教程不更新 MongoDB

node.js - MongoDB 分页聚合查找在海量数据中运行缓慢