The type 'DocumentArray<{ public_id: string; url: string; }>' is lacking the properties that are present in the type '{ public_id: string; url: string; }[]'

Issue: The type '{ public_id: string; url: string; }[]' is missing several properties from the type 'DocumentArray<{ public_id: string; url: string; }>': isMongooseDocumentArray, create, id, $pop, and more.

The error occurs at product.photos = photosURL;. However, it works fine when assigning values using

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;
    }

Current Product schema structure:

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,
  }));
};

Answer №1

The issue arises from the mismatch between assigning an array of plain objects ({ public_id: string; url: string; }[]) to a Mongoose DocumentArray (product.photos). This discrepancy causes an error because Mongoose expects a DocumentArray with specific methods, while you are providing a regular array.

To resolve this, you must map the array of objects (photosURL) into Mongoose subdocuments before assignment. Below is the revised code:

product.photos = photosURL.map(photo => ({
  public_id: photo.public_id,
  url: photo.url,
}));

Full Code:

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"],
      },
    },
  ],
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason behind eslint not permitting the rule option @typescript-eslint/consistent-type-imports?

Upon implementing the eslint rule, I configured it like this. module.exports = { rules: { "@typescript-eslint/consistent-type-imports": [ "error", { fixStyle: "inline-type-imports" ...

Storing user input as an object key in typescript: A comprehensive guide

When delving into Firestore for the first time, I quickly learned that the recommended modeling approach looks something like this: check out the model here members { id: xyz { name: Jones; ...

Tips for utilizing where/whereDate in MongoDB aggregate functions with the Jessengers package in your Laravel project

Is there a way to incorporate where/whereDate in an aggregate mongodb query ? I am utilizing an aggregate query within Laravel along with jenseger-mongodb for grouping fields. The issue I'm facing is that I require a condition to retrieve grouped da ...

What is the reason behind prettier's insistence on prefixing my IIAFE with ";"?

I've encountered async functions in my useEffect hooks while working on a JavaScript project that I'm currently transitioning to TypeScript: (async ():Promise<void> => { const data = await fetchData() setData(data) })() Previously, ...

I am not currently working on developing an angular application

Seeking assistance for the issue described below, as I have been struggling with it for three days. Any help would be greatly appreciated. Despite multiple attempts, the situation only seems to worsen with each try. The problem arises when attempting to ...

An endless cascade of dots appears as the list items are being rendered

Struggling to display intricately nested list elements, Take a look at the JSON configuration below: listItems = { "text": "root", "children": [{ "text": "Level 1", "children": [{ "text": "Level 2", "children": [{ "text": ...

Using $regex in mongodb's pipeline operations allows for advanced string

I need to be able to use $regex in order to search for any words that contain a specific keyword provided by the user, but I'm experiencing issues. Here's what I have so far: aggregatePipeline.push({ $match: { name: { $reg ...

Enhance the functionality of Immutable.js field by integrating a custom interface in Typescript

Imagine a scenario where the property name is field, essentially an immutable object. This means that methods like field.get('') and other immutable operations are available for use. Nevertheless, I have my own interface for this field which may ...

TypeScript is still throwing an error even after verifying with the hasOwnProperty

There exists a type similar to the following: export type PathType = | LivingstoneSouthernWhiteFacedOwl | ArakGroundhog | HubsCampaigns | HubsCampaignsItemID | HubsAlgos | HubsAlgosItemID | TartuGecko | HammerfestPonies | TrapaniSnowLeop ...

Bringing in a feature within the Vue 3 setup

At the moment, I am attempting to utilize a throttle/debounce function within my Vue component. However, each time it is invoked, an error of Uncaught TypeError: functionTD is not a function is thrown. Below is the code snippet: useThrottleDebounce.ts imp ...

Angular's observables were unable to be subscribed to in either the constructor or ngOnInit() functions

Currently, I am incorporating an observable concept into my application. In this setup, a service is called by component1 to emit an event that is then subscribed to by component 2. Below is the code snippet for reference: Service Code export class Mes ...

Encountering a console error in a TypeScript Express app when using MUI and Preact: "Unexpected prop `children` passed to `InnerThemeProvider`, was expecting a ReactNode."

I'm working on integrating MUI with a Preact app. In VSCode, everything seems to be set up correctly, but when I try to view it in the browser, nothing renders and I get this console error: react-jsx-runtime.development.js:87 Warning: Failed prop type ...

Would upgrading MongoDB from version 2.0.2 to 2.2 be a safe process with rollback contingency?

I'm considering upgrading MongoDB from version 2.0.2 to the latest release, but I have some concerns about running mongod with my current data files. If something were to go wrong during the upgrade process, would I be able to simply stop mongod and ...

Having trouble with Angular 5 tsconfig baseURL not functioning properly?

This may appear straightforward, but I am facing difficulties with it My Angular 5 application consists of three files located as follows: app_directory/tsconfig.json app_directory/src/app/services/my-service.service.ts app_directory/src/app/main/sub1/su ...

The 'data' parameter must be a string type or an object of Buffer, TypedArray, or DataView. Undefined value was received instead

Hello, I am attempting to use nodejs to write a file and store it in a mongodb database. However, I encountered an error stating "The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined" wh ...

Tips on implementing zod schema types with remapped fields using the toZod method

I'm currently working on mapping a schema key to a different name in my database interface Country { isoCode: string, nameEn: string, nameDe: string, phone: string, bla: string } const CountryJson = { i ...

Check to see if the ObjecticID is already present in the array or not

In my MongoDB database, I have created a column called history as an array for each user. This column stores the IDs of specific cards that the user has interacted with. Now, I want to implement a condition to check whether a card ID is already present in ...

Problem with storing an array of objects in MongoDB

Encountering difficulties when trying to add an array of objects to MongoDB, particularly related to the initialization of posts in ngOnInit() and the presence of an _id entry before constructing inviteGroup. https://i.sstatic.net/fogb4.png To resolve th ...

While utilizing the imodel.js front-end for designing a custom geometric model, I ran into an issue while trying to display it

Utilizing imodel.js front-end, I was able to design a customized geometric model featuring elements like a collection box. However, when placing the model within the existing SpatialViewState in bim, it failed to display properly in the current view. Sub ...

the undefined 'pipe' cannot be read

Trying to perform unit testing for an Angular component is a new experience for me. Currently, I am encountering a specific issue that I would like assistance with. The component in question contains the following select statement: this.store.select(getI ...