You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Sequelize中访问对象属性内的数组:表单同名输入返回数组场景

Accessing Array Properties from req.body in Sequelize

Great question! When your form sends multiple inputs with the same name, Express automatically parses those into arrays in req.body—which is exactly what you’re seeing with galery and exhibitionName. Working with these arrays in Sequelize is straightforward, and the approach depends on what you want to do with the data. Let’s break down the common scenarios:

1. Directly Access the Arrays from req.body

First, you can grab the arrays just like any other property on a JavaScript object:

const galeries = req.body.galery; // ["Perrotin","Moma",""]
const exhibitions = req.body.exhibitionName; // ["Lalala","..."]

A quick cleanup step is usually helpful here to remove empty strings (like the one in your galery array):

const cleanedGaleries = galeries.filter(item => item.trim() !== ''); // ["Perrotin","Moma"]
const cleanedExhibitions = exhibitions.filter(item => item.trim() !== ''); // ["Lalala","..."]

2. Use Arrays with a Model's Array-Type Field

If your Sequelize model has a field defined as an array (e.g., PostgreSQL’s ARRAY type or a JSON field that stores arrays), you can pass the cleaned array directly when creating or updating a record.

For example, if your Artwork model looks like this:

const Artwork = sequelize.define('Artwork', {
  artist: DataTypes.STRING,
  title: DataTypes.STRING,
  // ... other fields
  galery: DataTypes.ARRAY(DataTypes.STRING), // Array of strings
  exhibitionName: DataTypes.ARRAY(DataTypes.STRING)
});

You can create a new record like this:

await Artwork.create({
  artist: req.body.artist,
  title: req.body.title,
  yearBegin: req.body.yearBegin,
  // ... all other fields
  galery: cleanedGaleries,
  exhibitionName: cleanedExhibitions
});

3. Use Arrays with Associated Models (Many-to-Many/One-to-Many)

If the arrays represent related records (e.g., an artwork is shown in multiple galleries), you’ll need to use Sequelize’s association methods to link the records.

Let’s say you have two models: Artwork and Gallery, with a many-to-many relationship. Here’s how you can associate the galleries from your request:

// First create the artwork
const newArtwork = await Artwork.create({
  artist: req.body.artist,
  title: req.body.title,
  // ... other non-array fields
});

// Find or create each gallery from the cleaned array
const galleryRecords = await Promise.all(
  cleanedGaleries.map(galleryName => 
    Gallery.findOrCreate({ where: { name: galleryName } })
  )
);

// Extract the actual gallery instances (findOrCreate returns [instance, createdBoolean])
const galleryInstances = galleryRecords.map(record => record[0]);

// Associate the galleries with the artwork
await newArtwork.addGalleries(galleryInstances);

(Note: addGalleries is generated automatically by Sequelize when you set up a many-to-many association—adjust the method name to match your association setup.)

Quick Tips

  • Always validate the arrays: Check if they exist first (use req.body.galery || [] to avoid undefined errors) and clean them to remove empty or invalid entries.
  • Handle errors: Wrap your Sequelize operations in try/catch blocks to catch any database-related issues.

内容的提问来源于stack exchange,提问作者Kim Rose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:45:36