错误:输入 '{ public_id: string;网址:字符串; }[]' 缺少类型“DocumentArray<{ public_id: string; url: string; }>”中的以下属性:isMongooseDocumentArray、create、id、$pop 以及其他 8 个属性。
我在
product.photos = photosURL;
遇到错误
使用 await Product.create({photos: photosURL});
赋值时工作正常
export const updateProduct = TryCatch(async (req, res, next) => {
const { id } = req.params;
const { name, price, stock, category, description } = req.body;
const photos = req.files as Express.Multer.File[] | undefined;
const product = await Product.findById(id);
if (!product) return next(new ErrorHandler("Product Not Found", 404));
if (photos && photos.length > 0) {
const photosURL = await uploadToCloudinary(photos);
const ids = product.photos.map((photo) => photo.public_id);
await deleteFromCloudinary(ids);
product.photos = photosURL;
}
我在产品架构中有以下内容:
photos: [
{
public_id: {
type: String,
required: [true, "Please enter Public ID"],
},
url: {
type: String,
required: [true, "Please enter URL"],
},
},
],
const getBase64 = (file: Express.Multer.File) =>
`data:${file.mimetype};base64,${file.buffer.toString("base64")}`;
export const uploadToCloudinary = async (files: Express.Multer.File[]) => {
const promises = files.map(async (file) => {
return new Promise<UploadApiResponse>((resolve, reject) => {
cloudinary.uploader.upload(getBase64(file), (error, result) => {
if (error) return reject(error);
resolve(result!);
});
});
});
const result = await Promise.all(promises);
return result.map((i) => ({
public_id: i.public_id,
url: i.secure_url,
}));
};
发生错误的原因是您将普通对象数组 ({ public_id: string; url: string; }[]) 分配给 Mongoose DocumentArray (product.photos)。这种不匹配会导致错误,因为 Mongoose 需要具有特定方法的 DocumentArray,但您传递的是常规数组。
在分配对象之前,您需要将对象数组(photosURL)映射到 Mongoose 子文档中。这是更新后的代码:
product.photos = photosURL.map(photo => ({
public_id: photo.public_id,
url: photo.url,
}));
完整代码:
export const updateProduct = TryCatch(async (req, res, next) => {
const { id } = req.params;
const { name, price, stock, category, description } = req.body;
const photos = req.files as Express.Multer.File[] | undefined;
const product = await Product.findById(id);
if (!product) return next(new ErrorHandler("Product Not Found", 404));
if (photos && photos.length > 0) {
const photosURL = await uploadToCloudinary(photos);
const ids = product.photos.map((photo) => photo.public_id);
await deleteFromCloudinary(ids);
product.photos = photosURL.map((photo) => ({
public_id: photo.public_id,
url: photo.url,
}));
}
product.name = name;
product.price = price;
product.stock = stock;
product.category = category;
product.description = description;
await product.save();
res.status(200).json({
success: true,
product,
});
});
// Product Schema:
const productSchema = new mongoose.Schema({
name: String,
price: Number,
stock: Number,
category: String,
description: String,
photos: [
{
public_id: {
type: String,
required: [true, "Please enter Public ID"],
},
url: {
type: String,
required: [true, "Please enter URL"],
},
},
],
});