Reputation: 41
i have already seen this article : Mongoose model Schema with reference array: CastError: Cast to ObjectId failed for value "[object Object]"
But can't figure how can i solve my problem as i think i'm passing the correct value.
my category schema :
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);
product schema where i ref category:
const { ObjectId } = mongoose.Schema;
category: [
{
type: ObjectId,
ref: "Category",
required: true,
},
],
error i get :
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] } },
how i make the product :
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);
Upvotes: 0
Views: 683
Reputation: 870
Your problem is that fields.category is a string.You have to convert it to an array.
this should work :
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);
Upvotes: 0