I’m learning how to create a RESTFul API but I don’t know what happens in my JavaScript code that is causing the delete method to not work correctly. Always return a 505 or 404. Never 200.
Write a SQL delete statement works fine, for example:
delete from `birdwatchers` where `id` = 14
This is the Stack:
- NodeJs with ExpressJs
- Knex as ORM
- Sqlite as Database
Code:
DataBase Helper:
The problem could be here. knex documentation say about delete - del: “Resolves the promise / fulfills the callback with the number of affected rows for the query.” That’s what I write “count > 0” in the endpoint
Documentation capture:
Delete JS-Knex function helper:
function removeObservation(id) {
return db('birdwatchers').where({ id }).del()
}
Endpoint:
const express = require('express')
const Birds = require('./helpers/dbHelpers') // Bring Helper Functions()
const server = express()
server.delete('/api/observations/:id', (req, res) => {
const { id } = req.params;
Birds.removeObservation(id)
.then( count => {
if (count > 0) {
res.status(200).json({ message: `Observation with ID ${id} deleted!` })
} else {
res.status(404).json({ message: 'Observation not found. Check ID, probably do not exist' })
}
})
.catch(error => {
res.status(500).json({ message: 'Error retrieving data' })
})
})
There is two Tables. birds and birdwatchers. :
DB Schema with Knex:
exports.up = function(knex) {
// Birds table
return knex.schema
.createTable('birds', tbl => {
tbl.increments(); // 'id' field.. PrimaryKey <--
tbl.text('common_name', 125).notNullable();
tbl.text('scientific_name', 125);
tbl.string('description', 500);
})
// Watchers table
.createTable('birdwatchers', tbl => {
tbl.increments(); // 'id' field
tbl.text('watcher', 125).notNullable().index();
tbl.string('observation', 500).notNullable();
// Foreign Key info to 'birds' tables
tbl.integer('bird_id') // 1) Foreign Key. We connect to child tables with this FK
.unsigned() // Can't be a negative number
.notNullable()
.references('id') // 2) Reference the 'id' field
.inTable('birds') // 3) In this table
.onDelete('CASCADE')
.onUpdate('CASCADE');
})
};
Visual representation of both talbles:
birds:
birdwatchers: