Images are strictly forbidden from being defined as an array or an object within the Sequelize, Postgres, Node.js, and

I am having trouble with making a post request to the database. The datatype for images is a string and I need to be able to upload one, two, or multiple images.

What is the best way to store these images?

Below is my Posts model:

const Sequelize = require("sequelize");
const db = require("../config/database");

const Posts = db.define(
 "post",
{
id: {
  type: Sequelize.INTEGER,
  primaryKey: true,
  autoIncrement: true,
},
title: {
  type: Sequelize.STRING,
},
images: {
  type: Sequelize.STRING,
    }})

This is my post method:

 router.post(
"/",
[
upload.array("images", config.get("maxImageCount")),
imageResize,
 ],
 async (req, res) => {
const paths = await req.files.map((file) => ({ fileName: file.filename }));
Posts.create({
  title: req.body.title,
  images: paths,     
  }).then(
  () => {
    res.status(201).send({
      msg: "Upload successful",
    });
  },
  (validation) => {
    res.status(422).json({
      errors: validation.errors.map((error) => {
        return {
          fieldName: error.path,
          message: error.message,
        };
      }),
    });
    }
  );
 }
);

Why do I keep receiving an error when uploading images?

{
"errors": [
    {
        "fieldName": "images",
        "message": "Images cannot be an array or an object"
    }
]
}

Answer №1

In the provided code, you have declared const paths = ..., but later on in your Posts.create() function, you reference path without an "S". It seems like there might be a typo in your question because req.files.map() creates an array. The error message is likely indicating that you cannot insert an array into a column value directly.

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

Issues encountered when utilizing NodeJS in conjunction with SequelizeJS

I encountered a problem while working with SequelizeJS and NodeJS. When I run the npm bin/www command, I receive the following error message: EventEmitter#success|ok is deprecated, please use promise-style instead. Executing (default): CREATE TABLE IF ...

Retrieve the Final Element of an Array in a Mongoose Field

Below is my schema definition; ... edge: { name: [ { type: String } ], image: [ { type: String } ] }, user: { type: mongoose.Types.ObjectId, ref: 'users' }, ... I am looking ...

Enhancing data validation and converting strings to dates with Nest.js - DTO approach

Anticipating the upcoming request to adhere to the ISO 8601 standard timestamp format, something similar to "2023-12-04T15:30:00Z" (typically embedded as a string within JSON data that needs conversion to a JavaScript Date object). This is my Data Transfe ...

Encountering NoResourceAdapterError when using @admin-bro/nestjs alongside @admin-bro/sequelize and MySQL?

Encountering a similar issue with '@admin-bro/sequelize' NoResourceAdapterError: No compatible adapters found for the provided resource import { Database, Resource } from '@admin-bro/sequelize'; import { AdminModule } from '@admin- ...

Alert: Unresolved Promise Rejection Notification in the world of Express.js and Node.js!

Recently delving into the world of Node.js and Express.js, I've been attempting to incorporate the Shippo API into my E-commerce website. Unfortunately, I have encountered persistent errors that have proved challenging to troubleshoot despite numerous ...

"Displaying mongoose date in the HTML5 input type date format (dd/mm/yyyy) is a simple process that can

I have a structured data in MongoDB as shown below: var Person = new Schema({ "Name": { type: String, required: true }, "DOB": { type: Date, "default": Date.now } }); An instance of this schema is created using NodeJs with mongoose ODM: { "N ...

When making updates or inserting new values into a database, it's important to lock the table to prevent multiple connections and errors while conducting a SELECT operation in

I am looking to update and/or insert a String value containing both letters and numbers in a Postgres DB. This value needs to be incremented by +1 (using PHP string functions) every time an UPDATE operation is performed. In order to ensure that there are ...

Dealing with the mystery of the Next.js Stripe webhook elusive function error

I've been working on setting up a Stripe webhook in my NextJS app to write data to Firebase Firestore, but for some reason, stripe.webhook.constructEvent is showing up as undefined even though everything seems to be properly configured. I'm usin ...

What is the most efficient method for appending /.json to the conclusion of express routes?

I am currently transitioning a DJANGO API to Node.js and have been tasked with ensuring that routes support the .json extension at the end. For instance, sending a GET request to /users/:id/.json should return a JSON object representing the user. The cha ...

Is it possible to display only the <%body%> tag in ejs?

Is it possible to render only the <%-body%> in ejs? I have a sidebar with animations in my layout, and every time I click a link in the sidebar, it refreshes the entire page including the animation. Can the body be changed without refreshing the pa ...

Tips on fixing error ERR_INVALID_URL during Angular-cli installation

On my Windows 10 system, I successfully installed: Node.js version 16.13.0 NPM version 8.1.0 However, when attempting to run 'npm install -g @angular/cli', I encountered the following error message: npm ERR! code ERR_INVALID_URL npm ERR! ...

Unable to display image using EJS and Multer

While working on my node.js application, I encountered an issue with rendering the uploaded image file. I have successfully integrated multer to handle file uploads, and the images are being stored in the correct folder. However, when trying to display the ...

Guide to Displaying HTTP POST Request Response on Pug Template

Whenever a user interacts with the form, I initiate an HTTP POST request to the database server. Subsequently, the database server sends a POST request back to the user's server. The issue I am facing is the inability to display this database result ...

Steps to create a private route in Express:

In my current project, I am utilizing a nodejs/express application as the backend solution. This application incorporates passport-jwt to secure specific routes using JWT as the header Authorization. One of these secured routes, known as secure-route, need ...

Organizing Your Express.js Project

After discovering Express's application generator, I noticed that the documentation lacks information on the purpose of each directory and file. Can someone provide a brief explanation of where specific files should be placed within this generated app ...

What is the best way to integrate Devise with a React frontend directory for my project?

I am currently working on a project that utilizes Rails and jbuilder with a react redux frontend. I am facing challenges when it comes to integrating devise with react and redux. Can you provide some guidance on how to go about this? Specifically, I am str ...

Challenges with NPM testing

Are there any reported issues with npm on Ubuntu 18.04? Or are there known solutions to the 100:1 error? I am currently enrolled in a course and it's crucial for me to be able to execute code using npm test. Despite multiple attempts at deleting and ...

Issue on Heroku with Discord.js displaying a "Service Unavailable" message

Encountered a strange error while trying to launch my discord bot on heroku. Previously, I implemented a command handler for the bot to organize commands in separate files but faced multiple code errors. With the help of a member from this community, all e ...

The get method of the nodejs express server requires three arguments

Could you provide clarification on the code snippet below? It appears that the get method is accepting 3 arguments instead of the typical 2. How does it handle the third argument which is an object? app.get('/query', function(req, res) { ...

Having trouble inserting a file into the mongoDB database due to an issue with the Path name being mandatory

I am currently trying to understand the process involved in adding a document to a MongoDB database. However, when attempting to add a document, I encounter the following error: { "errors": { "name": { "message": "Path `name` is required.", "name": " ...