I’ve been struggling with how to grab the images in an array of objects that looks like this:
import mongoose from "mongoose";
const prodcutSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
trim: true,
lowercase: true,
unique: true,
},
details: [String],
fits: [String],
compositions: [String],
sold: {
type: Number,
default: 0,
},
colors: [
{
coverImage: {
type: String,
required: true,
},
hoverImage: String,
images: [String],
colorName: {
type: String,
required: true,
trim: true,
lowercase: true,
},
colorQuantity: {
type: Number,
required: true,
trim: true,
},
discount: {
type: Number,
default: 0,
max: 80,
},
sizes: [
{
sizeName: {
type: String,
required: true,
trim: true,
lowercase: true,
},
sizeQuantity: {
type: Number,
required: true,
trim: true,
},
},
],
},
],
price: {
type: Number,
required: true,
trim: true,
},
totalQuantity: {
type: Number,
required: true,
trim: true,
},
category: {
type: mongoose.Schema.ObjectId,
ref: "Category",
required: true,
},
subcategory: {
type: mongoose.Schema.ObjectId,
ref: "Subcategory",
required: true,
},
series: {
type: mongoose.Schema.ObjectId,
ref: "Series",
required: true,
},
},
{ timestamps: true }
);
That is the schema of the object, and i dont know how to add that path for the images in my router, i have it like this:
router.post("/", upload.fields([
{
name: "coverImage",
maxCount: 1,
},
{
name: "hoverImage",
maxCount: 1,
},
{
name: "images",
maxCount: 3,
},
]), createProdcutValidation, createProduct);
And is always throwing me an “MulterError: Unexpected field” this is how i send it with postman:
Postman Image
So what is the problem?
“MulterError: Unexpected field” i always get this error!
As files are within an array of objects, .fields()
cannot detect fields, and it’s giving that error (fieldname
is actually colors[0][coverImage]
etc., which is then unexpected…).
You could use .any()
, to process all files, and then you could loop req.files
and read fieldname
property to determine which type of file is it, add counter to replace maxCount
, validate etc.
For example:
router.post("/", upload.any(), createProdcutValidation, createProduct);
handle and validate:
req.files.forEach(file => {
// handle/validate
console.log(file.fieldname); // e.g. 'colors[0][coverImage]'
});