Insert multiple records into MySQL using NODEJS

0

How do I add multiple records at once in MySQL by passing an array of, for example, products?

HTTP-POST request, where products is an array with an x number of products. FRONT-END

  addProduct(products: any): Observable<any> {
    return this.http.post<any>(this.productURL, products, httpOptions)
  }

BACK-END

// Add Products  
app.post('/products', function (req, res) {

    let products = req.body;
    console.log(products)

    if (!products) {
        console.log('Deu erro na bagaça')
        return res.status(400).send({ error: true, message: 'Please provide products' });
    }

    mydb.query('INSERT INTO products SET ${products} ', function (error, results, fields) {
        if (error) throw error;
        // console.log(results)
        return res.send(results);
    });
});

console.log () in the BACK-END of the variable sent to the back

    
asked by anonymous 04.12.2018 / 16:51

1 answer

0

Given that the names of your fields in the table are the same as those given in the question, your code would look like this:

const values = products.map((product) => {
  return [
    product.ProductName,
    product.ProductElement,
    product.ProductAttribute,
    product.ProductAttributeValue,
    product.Quantity,
    product.ProductNotes,
    product.FK_ID_QUOTE,
    product.GroupNumber,
    product.ID_POF,
    product.ID_POE
   ]);
});

mydb.query('INSERT INTO products (ProductName, ProductElement, ProductAttribute, ProductAttributeValue, Quantity, ProductNotes, FK_ID_QUOTE, GroupNumber, ID_POF, ID_POE) VALUES ?', values, function (error, results, fields) {
  if (error) throw error;
  // console.log(results)
  return res.send(results);
});

You would transform the array of products into a array of values and so you would insert into the table.

    
04.12.2018 / 17:03