1

I am creating an API using Node.Js and MySQL and I am trying to structure the data when it is returned.

I am POSTing the following to create a new record

{
    "SiteName" : "My Site",
    "PitchTypes" : {
        "TentPitches": true
    }
}

This creates a new entry into the database correctly and then returns the data. However, it is returning the following. How can I format the data into the same format it was submitted in.

{
    "id": 1,
    "SiteName": "My Site",
    "TentPitches": true
}

I have the following in my model and controller

campsite.models.js

exports.create = (req, res) => {
  // Validate request
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
  }
  
  // Create a Record
  const campsite = new Campsite({
    SiteName: req.body.SiteName,
    TentPitches: req.body.PitchTypes.TentPitches
  });
  
  // Save Campsite in the database
  Campsite.create(campsite, (err, data) => {
    if (err)
    res.status(500).send({
      message:
      err.message || "Some error occurred while creating the Campsite."
    });
    else res.send(data);
  });
};

campsite.controllers.js

const Campsite = function(campsite) {
  this.SiteName = campsite.SiteName;
  this.TentPitches = campsite.TentPitches;
  
};

Campsite.create = (newCampsite, result) => {
  sql.query("INSERT INTO campsites SET ?", newCampsite, (err, res) => {
    if (err) {
      console.log("error: ", err);
      result(err, null);
      return;
    }
    
    console.log("created campsite: ", { id: res.insertId, ...newCampsite });
    result(null, { id: res.insertId, ...newCampsite });
  });
};

my MySQL database has the following table

CREATE TABLE `campsites` (
    `Id` int(5) NOT NULL AUTO_INCREMENT,
    `SiteName` varchar(256) NOT NULL,
    `TentPitches` tinyint(1),
    `TentPitches_Electric` tinyint(1),
    PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
5
  • are you using sequelize npm for mysql? Commented Sep 18, 2020 at 10:18
  • @PramodKharade No I'm not at the minute, just using the following packages: mysql, express, body-parser Commented Sep 18, 2020 at 10:20
  • after inserting the record in database, it is return either error or response so you can modify the response before passing to the result Commented Sep 18, 2020 at 10:28
  • Ahh, so where it says res.send(data) in the model, it's returning the data it's created so I can manipulate it here to appear in a different format. Commented Sep 18, 2020 at 10:29
  • 1
    Yes. before passing res.send(data) data to send method . you can modified as per need and store in any const variable . pass that final object to send method Commented Sep 18, 2020 at 10:33

1 Answer 1

1

I am assuming, You will receive the response format as below:

{
    "id": 1,
    "SiteName": "My Site",
    "TentPitches": true
}

Before send response to send method res.send(data) you can modify the response as you are expecting as below:

{
    "SiteName" : "My Site",
    "PitchTypes" : {
        "TentPitches": true
    }
}

You can modify as below:

    const data = {
          "id": 1,
          "SiteName": "My Site",
          "TentPitches": true
      };
     
      let modifyResult={};
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          if(key==="TentPitches"){
          modifyResult["PitchTypes"]={TentPitches:data[key]};
          }else{
          modifyResult[key] =data[key];
          }
        }
      }

// res.send(modifyResult); Here you can pass the object

it may not be best solution but some what it will give idea around the problem.

Hope, it will solve your problem.

const data = {
          "id": 1,
          "SiteName": "My Site",
          "TentPitches": true
      };
     
      let modifyResult={};
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          if(key==="TentPitches"){
          modifyResult["PitchTypes"]={TentPitches:data[key]};
          }else{
          modifyResult[key] =data[key];
          }
        }
      }
// res.send(modifyResult); Here you have pass the modify object
console.log("Result is:",modifyResult);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.