【问题标题】:CastError: Cast to Array failed for valueCastError:转换为数组的值失败
【发布时间】:2023-04-09 00:33:02
【问题描述】:

当我收到来自 post 的数据并尝试对其进行解析时,出现了错误。

这是有关问题的详细信息:

我有两个模型:

var tags = require('../tag/tag.model'),
  mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var OpportunitiesSchema = new Schema({
    employeeTitle: String,
    tagline: Boolean,
    description:String,
    location:String,
    isPreferred:Boolean,
    tags: [
      {
        type:Schema.Types.ObjectId,
        ref:'Tag'
      }
    ]
});

module.exports.opportunities = mongoose.model('Opportunities', OpportunitiesSchema);

我还有另一个模型:

var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var TagSchema = new Schema({
  id: Number,
  name: String
});

module.exports = mongoose.model('Tag', TagSchema);

我的功能是这样的:

var Opportunities = require('./opportunities.model').opportunities;
exports.create = function(req, res) {
  //addOpportunitites.save(req.body, function(err, tag) {
  //    if(err) { return handleError(res, err); }
  //    return res.json(201, tag);
  //});

  var newOpportunity = new Opportunities(req.body);

  newOpportunity.save(function(err) {
    if(err) {
      console.log(err);
    } else {
      return res.json(201);
    }

  })
};

当我发送这样的数据时:

{
  "employeeTitle": "Digital Agency Employee, downtown Chicago",
  "tagline": "My company is offering $1000 referral bonus and I'll give you half!",
  "description": "<p>Looking for someone who has the following abilities: <ul><li></li></ul></p>",
  "location": "",
  "tags": [
    545454,45467
  ]
}   

有一个错误:

{
    [ValidationError: Opportunities validation failed]
    message: 'Opportunities validation failed',
    name: 'ValidationError',
    errors: {
        tags: {
            [CastError: Cast to Array failed for value "545454,45467" at path "tags"]
            message: 'Cast to Array failed for value "545454,45467" at path "tags"',
            name: 'CastError',
            kind: 'Array',
            value: [Object],
            path: 'tags',
            reason: undefined
        }
    }
}

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    在tags 中,您发送Numbers,大概是标签模型中的id,但在Opportunities 模型中,您存储的是ObjectIds,即_id由 mongo 生成。

    【讨论】:

    • 这取决于你的代码的其余部分是什么样的,以及你想要来回传递给前端的数据类型。如果您将 POST 数据的 tags 更改为 ObjectID 作为字符串(例如 "561fa3aac09d1fa4eb63f806"),我希望它能够按原样工作。或者,您可以使用当前的 id 字段在后端的控制器中查找它们。
    猜你喜欢
    • 2020-08-25
    • 2021-06-27
    • 2021-09-05
    • 2019-04-18
    • 2018-11-06
    • 2015-10-29
    • 2022-01-23
    • 2021-03-14
    • 2014-06-20
    相关资源
    最近更新 更多