【问题标题】:Automatically parse some fields to string on mongoose?自动将某些字段解析为猫鼬上的字符串?
【发布时间】:2022-01-16 23:55:03
【问题描述】:

我有一个像这样的对象

{
  name: 'abc',
  value: BigNumber('125'),
  other: {
    otherValue: BigNumber('252'),
  }
}

它的猫鼬模式是:

{
  name: { type: String, required: true },,
  value: { type: String, required: true },,
  other: {
    otherValue: { type: String, required: true },,
  }
}

有没有办法在存储对象之前自动将valueotherValue 解析为字符串(通过调用.toString()),或者唯一的方法是手动解析?

【问题讨论】:

    标签: typescript mongoose


    【解决方案1】:

    Mongoose 允许在您的架构中使用 set 属性,该属性将用于在插入之前更改值。

    您可以使用此 set 属性来“字符串化”您的值。

    {
      name: { type: String, required: true },
      value: { type: String, required: true, set: (val) => val.toString()},
      other: {
        otherValue: { type: String, required: true, set: (val) => val.toString() },
      }
    }
    

    【讨论】:

      【解决方案2】:

      你试过这样吗?

      {
        name: 'abc',
        value: BigNumber(125).toString(),
        other: {
          otherValue: BigNumber(252).toString(),
        }
      }
      

      {
        name: 'abc',
        value: BigInt(125).toString(),
        other: {
          otherValue: BigInt(252).toString(),
        }
      }
      

      {
        name: 'abc',
        value: 125n.toString(),
        other: {
          otherValue: 252n.toString(),
        }
      }
      

      示例结果:

      【讨论】:

        猜你喜欢
        • 2019-06-16
        • 1970-01-01
        • 2023-01-19
        • 1970-01-01
        • 1970-01-01
        • 2016-04-28
        • 2014-06-10
        • 1970-01-01
        • 2021-11-07
        相关资源
        最近更新 更多