0

I'm creatin CRUD operations in Express, and I want to test this on simply array in the same file. My problem is that everything is working but delete or post request doesn't update that array's items. What am I doing wrong ??

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
app.use(cors());

app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
let cats = [
  {
    id: 1,
    title: "Filemon",
    color: "black"
  },
  {
    id: 2,
    title: "Burys",
    color: "fire"
  },
  {
    id: 3,
    title: "Mysia",
    color: "Grey"
  },
  {
    id: 4,
    title: "Niunia",
    color: "Black - grey"
  }
];
app.get("/api/cats", (req, res) => {
  res.send(cats);
});
app.get("/api/cats/:id", (req, res) => {
  res.send(cats.find(t => t.id === parseInt(req.params.id)));
});

app.post("/api/cats", (req, res) => {
  let cat = {
    id: cats[cats.length - 1].id + 1,
    title: req.body.title
  };
  cats.push(req.body);
  res.send(cat);
});

I want to add cat with dynamic id depending of last cat's id. When I add one cat his id is 5 but when I add next his id is undefined because my array is not updated. How to fix this ?

Freestyle09
  • 4,894
  • 8
  • 52
  • 83

1 Answers1

1
app.post("/api/cats", (req, res) => {
  let cat = {
    id: cats[cats.length - 1].id + 1,
    title: req.body.title
  };
  cats.push(req.body);
  res.send(cat);
});

cats.push(req.body); should read cats.push(cat); you need to be pushing the new object into your cats array. However this is not permanent and any time you restart the server the data will revert to as is laid out in the initial cats declaration. For permanent data you need to store this info in a DB.

CalamityAdam
  • 354
  • 1
  • 6
  • 15