我一直在努力研究如何抓取如下所示的对象数组中的图像:
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 }
);
这是对象的模式,我不知道如何在路由器中添加图像的路径,我有这样的:
router.post("/", upload.fields([
{
name: "coverImage",
maxCount: 1,
},
{
name: "hoverImage",
maxCount: 1,
},
{
name: "images",
maxCount: 3,
},
]), createProdcutValidation, createProduct);
并且总是向我抛出“MulterError:意外字段”,这就是我用邮递员发送它的方式: 那么问题出在哪里呢?
“MulterError:意外字段”我总是收到此错误!
由于文件位于对象数组中,
.fields()
无法检测字段,因此会出现该错误。
.any()
来处理所有文件,然后您可以循环req.files
并读取fieldname
属性来确定它是哪种类型的文件,添加计数器来替换maxCount
,验证等
例如:
router.post("/", upload.any(), createProdcutValidation, createProduct);
处理和验证:
req.files.forEach(file => {
// handle/validate
console.log(file.fieldname); // e.g. 'colors[0][coverImage]'
});