【问题标题】:Mongoose model Schema with reference array: CastError: Cast to ObjectId failed for value "["5f09b....,5f0d...."]"带有参考数组的猫鼬模型架构: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);

【问题讨论】:

    标签: node.js reactjs mongodb mongoose


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2017-08-14
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 2017-02-06
      • 2020-10-21
      • 2021-01-07
      • 2017-03-23
      • 2015-08-10
      相关资源
      最近更新 更多