【问题标题】:Mongoose save model with object field带有对象字段的猫鼬保存模型
【发布时间】:2018-01-18 07:02:07
【问题描述】:

我正在尝试保存具有带有对象字段的架构的猫鼬模型。当我尝试保存时,出现以下错误。我错过了什么?

我怀疑这可能与 mongoose 对象不太像标准的 javascript 对象有关,因为它们已被更改。但是,让我感到困惑的是,我在代码的另一部分中使用具有嵌套对象字段并且有效的架构做完全相同的事情。

我尝试过的:

  • 为了进行测试,我将架构更改为将 resulttype 和 resultround 作为单独的字段列出,没有嵌套,并且当我这样做时它起作用了。
  • 我还尝试使用我的模型之外的键值对创建一个对象,然后将该对象传递给我的模型。那也没有用。

架构

 var ResultSchema = new mongoose.Schema({
    event_id : mongoose.Schema.ObjectId,
    event_name: String,
    event_type: String,
    resultdate : String,
    resulttype: {
        type: String, 
        round: Number
    },
    // resulttype: String,
    // resultround: Number,
 });

模型保存:

var newResult = new ResultModel({
    // objNewResult
    event_id: req.body.eventid,//hidden field
    event_name: req.body.eventname, //hidden field
    resultdate: req.body.resultdate,
    // resulttype: resulttypelist,
    // resultround: resultroundlist,
    resulttype: {
        type: req.body.resulttypelist, 
        round: req.body.resultroundlist
    }
});

newResult.save(function (err, result) {
        if (err) {
            console.log("SOMETHING WENT WRONG");
            console.log(err);
        } else {
            console.log("SUCCESSFUL RESULT ADDITION");
        }
    });

错误:

ValidationError: results validation failed: resulttype: Cast to String failed for value "{ type: 'standard', round: '1' }" at path "resulttype"

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    type 是 Mongoose 模式中的保留关键字。它用于指定字段的类型。当您指定时:

    resulttype: {
        type: String, 
        round: String
    },
    

    Mongoose 会将字段 resulttype 视为字符串。所以你必须使用其他名称而不是类型。

    【讨论】:

      【解决方案2】:

      type 是保留键:

      默认情况下,如果您的架构中有一个带有键“type”的对象,mongoose 会将其解释为类型声明。 Source.

      所以现在,resulttype 应该是 String 类型。您可以改用其他密钥:

      架构

      resulttype: {
        resultType: String, 
        round: String
      },
      

      模型保存:

      var newResult = new ResultModel({
        // ...
      
        resulttype: {
          resultType: req.body.resulttypelist, 
          round: parseFloat(req.body.resultroundlist),
        }
      });
      

      【讨论】:

      • 这是一个很好的建议,但这是我的一个错字。我已编辑架构以显示 round 的字符串。我仍然遇到同样的错误。
      • 为了测试,我将架构保留为数字,但当我投射用户 parseInt 或 parseFloat 时仍然出现相同的错误。 message: 'Cast to String failed for value "{ type: \'standard\', round: 1 }" at path "resulttype"', name: 'CastError', stringValue: '"{ type: \'standard\', round: 1 }"',
      • 好的。谢谢。这就是问题所在。我标记了 MikaS 提供的答案,因为他们首先根据我看到的时间戳给出了正确的答案。
      猜你喜欢
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多