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!