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 ?

8
  • 2
    cats.push(req.body); why are you doing this here? You should have pushed the newly created object. No? Commented Dec 10, 2018 at 12:50
  • Yeah, my mistake... Id is working well now, but It's not saving array, Can I do this ? When I restart server my cat's are gone... Commented Dec 10, 2018 at 12:52
  • 1
    You have to keep your cats in a DB then. Once the node process is dead, the associated memory will be flushed. Commented Dec 10, 2018 at 12:53
  • So I cannot update file with this, like in json-server ? Commented Dec 10, 2018 at 12:54
  • 2
    @Freestyle09 well for that you need to write data of your array to some file and read up from there. Commented Dec 10, 2018 at 12:54

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.