【问题标题】:Mongoose Schema not Casting in Object's Built-in Getter as ExpectedMongoose Schema 未按预期在对象的内置 Getter 中进行转换
【发布时间】:2018-07-05 07:12:13
【问题描述】:

我刚刚遇到了一个意想不到的猫鼬行为,想和熟悉猫鼬的人确认一下。

我理解mongoose guide on schemas 的意思是它会自动转换为指定的数据类型每当您引用架构的属性时。指南中使用的语言相当笼统,可能含糊不清:

我们的代码 blogSchema 中的每个键都在我们的文档中定义了一个属性 它将被转换为其关联的 SchemaType。例如,我们已经 定义了一个属性标题,它将被转换为 String SchemaType 和属性 date 将被转换为 Date SchemaType。

根据我最近的发现,它似乎不像我想象的那样普遍。

我有一个包含amounttransaction 架构,如下所示:

let transactionSchema = mongoose.Schema({

    ...

    amount: { type: Number, required: true },
    description: { type: String, required: true },

从我的客户端,我的 HTML 将输入提交给路由器,并分配 req.body 参数,如下所示:

router.post('/save', function(req, res) {

    let theTransaction = {
        _id: req.body.transactionId,

        ...

        amount: req.body.amount,
        description: req.body.description,

据我了解,HTML 将字符串发送回路由器,因此req.body.amount 实际上是一个字符串。我允许mongoose保存,保存的版本就没有问题了。

但是,假设theTransaction.amount = 500。当我引用要保存的theTransaction 对象时,我看到555 + theTransaction.amount = 555500.00,而不是1055。

这是我的测试:

console.log("transaction.amount");       \\transaction.amount
console.log(transaction.amount);         \\500.00
console.log(typeof transaction.amount);  \\string
let nmbr = 555;
nmbr += transaction.amount;
console.log("nmbr");                      \\nmbr
console.log(nmbr);                        \\555500.00
console.log(typeof nmbr);                 \\string

看到这个我很惊讶。我假设 mongoose 会在其内置的 getter 中为模式执行强制转换。我开始寻找,发现你可以create your own getters in a mongoose schema

我可以理解特殊用途的 getter 的用途,例如 mongoose 文档示例中所示的那些。但是,我不明白为什么 mongoose 会被设计为要求我为我创建的每个基本类型创建一个 getter。

我是在滥用猫鼬,还是必须在我的模式中添加大量吸气剂?还是有其他方法可以解决这个问题?

谢谢。

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    如果不查看文档代码,很难判断您是否正确创建了文档,因此我无法直接帮助您解决问题。不过,我可以验证在 Mongoose 中的投射效果非常好。

    const assert = require('assert');
    const mongoose = require('mongoose');
    
    const toySchema = new mongoose.Schema({
      name: { type: String },
      cost: { type: Number }
    });
    
    const Toy = mongoose.model('Toy', toySchema);
    
    const toy = new Toy({
      name: 'Blaster',
      cost: '10.00'
    });
    
    assert.equal(typeof toy.cost, 'number'); // Passes
    assert.strictEqual(toy.cost, 10.00); // Passes
    

    【讨论】:

    • 谢谢,杰森。我很高兴知道这一点。你帮我揭露了这个问题。我创建 theTransaction 时没有使用新的架构对象。
    • @JeffMatthews 很高兴听到它有帮助!
    猜你喜欢
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    相关资源
    最近更新 更多