Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

330
Vistas
Post Multiple items / an array with Express & Postman

unfortunately I have problems to post an Array to my Express Server. I post an item and if it exists in the db it will be deleted.

My code:

item.routes.js

module.exports = app => {
    
  const item = require("../controllers/item.controller.js");

  app.post("/itemr", item.IsReserved);
};

item.controller.js

const Item = require("../models/item.model.js");

exports.IsReserved = (req, res) => {
  // Validate request
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
  }

  const item = new Item({
    itemId: req.body.assetId,
    botId: req.body.botId,
  });

  Item.IsReserved(item, (err, data) => {
    if (err)
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Item(db)."
      });
    else res.send(data);
  });
};

item.model.js

const sql = require("./db.js");

Item.IsReserved = (RItem, result) => {
    sql.query(`SELECT * FROM ReservedItems WHERE itemId = "${RItem.itemId}"`, (err, res) => {
        if(res.length){
            sql.query(`DELETE FROM ReservedItems WHERE itemId = "${RItem.itemId}"`, (err, res) => {
                if (err) {
                    console.log("error: ", err);
                    result(err, null);
                    return;
                }
                result(null, { id: res.insertId, ...RItem });
            });
        }
        else{
            result(null, { message: "nothing to do"});
        }
    });
};


module.exports = Item;

A single item works great with a post like this:

{
   "assetId" : 3,
   "botId" : "1"
}

but if I want to insert multiple items like this:

[
    {
        "assetId" : 3,
        "botId" : "1"
        },
        {
        "assetId" : 4,
        "botId" : "1"
    }
]

The result from this is "nothing to do"...

My sql log shows: Query SELECT * FROM ReservedItems WHERE itemId = "undefined"

I saw another post here which had a similar problem, but I don't know how to implement something like ".create()" into my code to recognize multiple items.

I would be very thankful for every answer!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

There are many approaches to fix your problem :)

First of all in your controller, this is not possible anymore as you send an array of items in your request payload. So you need to define an array aswell :

  const items = req.body.map((item) => new Item({
    itemId: item.assetId,
    botId: item.botId,
  });

As your method IsReserved handles only 1 item, you can use Promise.all to apply modifications. Something like this :

Promise.all( items.map( (item) => Item.isReserved(item)))
.then( (result) => ...do something here)
.catch( (error) => ...do something else here)

Another approach could be to change the SQL statement and use WHERE IN

SELECT * FROM ReservedItems WHERE itemId IN (itemid1, itemid2...)

This will get you an array of items that you can then delete the same way. It seems better in terms of performance.

I also recommand to use async/await syntax as it's way easier to read code containing promises

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda