带有参考数组的猫鼬模型架构:CastError: Cast to ObjectId failed for value "["5f09b....,5f0d...."]&qu

Posted

技术标签:

【中文标题】带有参考数组的猫鼬模型架构:CastError: Cast to ObjectId failed for value "["5f09b....,5f0d...."]"【英文标题】:Mongoose model Schema with reference array: CastError: Cast to ObjectId failed for value "["5f09b....,5f0d...."]" 【发布时间】:2020-11-08 04:07:09 【问题描述】:

我已经看过这篇文章了:Mongoose model Schema with reference array: CastError: Cast to ObjectId failed for value "[object Object]"

但不知道如何解决我的问题,因为我认为我传递了正确的值。

我的类别架构:

const mongoose = require("mongoose");

const categorySchema = new mongoose.Schema(
  
    name: 
      type: String,
      trim: true,
      required: true,
      maxlength: 32,
      unique: true,
    ,
  ,
   timestamps: true 
);

module.exports = mongoose.model("Category", categorySchema);

我引用类别的产品架构:

const  ObjectId  = mongoose.Schema;
category: [
  
    type: ObjectId,
    ref: "Category",
    required: true,
  ,
], 

我得到的错误:

Error: Product validation failed: category: Cast to [ObjectId] failed for value "["5f09bc7d75350639906e0822,5f0df6442400aa0344d64347"]" at path "category"

stringValue: '"["5f09bc7d75350639906e0822,5f0df6442400aa0344d64347"]"',
messageFormat: undefined,
kind: '[ObjectId]',
value: '["5f09bc7d75350639906e0822,5f0df6442400aa0344d64347"]',
path: 'category',
reason: [CastError]  ,

我如何制作产品:

form.parse(req, (err, fields, file) => 
    if (err) 
      return res.status(400).json(
        error: "Problem with image",
      );
    
    //destructure the fields
    const  name, description, price, category, stock  = fields;
    if (!name || !description || !price || !category || !stock) 
      return res.status(400).json(
        error: "All fields are required!",
      );
    
    //TODO : rescrition on fields
    let product = new Product(fields);

【问题讨论】:

【参考方案1】:

您的问题是 fields.category 是一个字符串。您必须将其转换为数组。

这应该可行:

form.parse(req, (err, fields, file) => 
        if (err) 
          return res.status(400).json(
            error: "Problem with image",
          );
        
        //destructure the fields
        const  name, description, price, category, stock  = fields;
        if (!name || !description || !price || !category || !stock) 
          return res.status(400).json(
            error: "All fields are required!",
          );
        
        fields.category = category.split(",");
        //TODO : rescrition on fields
        let product = new Product(fields);

【讨论】:

以上是关于带有参考数组的猫鼬模型架构:CastError: Cast to ObjectId failed for value "["5f09b....,5f0d...."]&qu的主要内容,如果未能解决你的问题,请参考以下文章

具有角色的参考数组的猫鼬模式

用于多个对象数组的猫鼬嵌套模式

带有数组的猫鼬模式

带有数组的猫鼬模式

我必须过滤带有数组的数组的猫鼬数据?

如何基于作为参数传递的动态模式的猫鼬模型?