0

Im sending a request with data as an array of objects:

 [
  {id: "1"},
  {id: "2"},
  {id: "3"}
 ]

im using JSON.stringify() and my req.body looks like this: { '{"id":"1"},{"id":"2"},{"id":"3"}': '' }

Now i want to loop through req.body and get all the ids so i can delete them from the SQL DB. Im using Sequelize. The back end:

exports.deleteIds = (req, res, next) => {
    console.log(req.body)
//here should be loop so i can delete all the ids one by one.
    Model.destroy({
        where: {
            id: 
        }
    })
}

The post request (client):

let ids = []
//maybe here is the problem?
for (var i = 0; i < selectedRow.length; i++) {
   ids.push({id:selectedData[i].id})          
}

let Url = "/admin/deleteIds"
let data = JSON.stringify(ids)

event.preventDefault();

$.post(Url, data, function (data, status) {

  }).done(function (res) {
     if (res.ids.length == 0) {
        $('#mainContent').html('<h1>0 users found</h1>')
     }
  })
  .fail(function (err) {
    console.log(err.responseJSON.message)
  })
3
  • which db library are you using?, it might be a built it option Commented Sep 16, 2020 at 22:38
  • @Itamar im using Sequelize Commented Sep 16, 2020 at 22:51
  • see my answer below Commented Sep 16, 2020 at 22:51

2 Answers 2

2

EDIT

We we do is all even easier, by sending and array of ids and using it in the server directly.

Client:

let ids = []
for (var i = 0; i < selectedRow.length; i++) {
   ids.push(selectedData[i].id)  // <-- this is the change         
}

let Url = "/admin/deleteIds"
let data = {items: ids}
//...

Server:

exports.deleteIds = (req, res, next) => {
   const ids = req.body.items; // <-- no mapping needed
   Model.destroy({
      where: {id: ids}
   })
}

POST calls body should be a valid JSON, which means that it should be an js object.

Assuming you use Fetch

Sending data to server with Fetch API

 const rawResponse = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({items:  [ {id: "1"}, {id: "2"}, {id: "3"} ]})
  });

First, if you get the req.body as an object, there is no reason to use JSON.stringify. if not use JSON.parse or Express's body-parser

Second you probably have a way in the DB library to send multiple IDs to destroy.

If you use Sequelize.js for example:

exports.deleteIds = (req, res, next) => {
   const ids = req.body.items.map(({id}) => id); 
   Model.destroy({
      where: {id: ids}
   })
}

In case this option does not exist, lets loop:

exports.deleteIds = (req, res, next) => {
   req.body.items.forEach(({id}) => {
      Model.destroy({
        where: {id}
      })
  }) 
}

Your fixed POST call:

let ids = []
for (var i = 0; i < selectedRow.length; i++) {
   ids.push({id:selectedData[i].id})          
}

let Url = "/admin/deleteIds"
let data = {items: ids} // <-- this is the change

event.preventDefault();

$.post(Url, data, function (data, status) {

  }).done(function (res) {
     if (res.ids.length == 0) {
        $('#mainContent').html('<h1>0 users found</h1>')
     }
  })
  .fail(function (err) {
    console.log(err.responseJSON.message)
  })
Sign up to request clarification or add additional context in comments.

11 Comments

Im using body parser as a middleware already. when im trying to send the post request with the array of object without JSON.stringify [ {id: "1"}, {id: "2"}, {id: "3"}] ,im getting { undefined: [ '', '', '' ] } (when console.log req.body)
can you add to the question the client post call and post server handler?
Thank you, i will try it, so just to make sure i can change my code this line so i will have the same code like you to get valid json datalet data = JSON.stringify({items: ids})
I did the solution on the top. but i changed one thing and its working perfect. i post the data without JSON.stringify: {items: [ {id: "1"}, {id: "2"}, {id: "3"} ]} and its working
edit your answer and delete the JSON.stringify from the solution. i choose to do it with const ids = req.body.items.map(({id}) => id); and its working good thank you.
|
0

As another user mentions, req.body should always be valid json, so receiving an array is unlikely.

When you receive a valid json request, in Sequelize you can use three methods:

  1. A get() function that determines what you retrieve from the database: https://sequelize.org/master/manual/getters-setters-virtuals.html

  2. A set() method on the model that runs a function on what you want to save to the database:

const User = sequelize.define('user', {
  username: DataTypes.STRING,
  password: {
    type: DataTypes.STRING,
    set(value) {
      this.setDataValue('password', hash(value));
    }
  }
});

  1. (Probably my recommendation here) A function directly on the controller, like in this example where I slugify an organization name:
  try {
    const result = await Organization.create({
      name: req.body.name,
      type: req.body.type,
      slug: slugify(req.body.name, { lower: true, remove: /[*+~.()'"!:@]/g, strict: true }),
      fields: allowedFields
    }) catch(err) { etc.}

2 Comments

Object keys would not work as it's was an array in the question
Sorry Itamar, I missed that. Will update. The create function I suggest is just an example on how to use the inline Model controller function possibility in Sequelize

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.