1

Is it possible to add a custom response in Express JS, like add an attribute that not exists in the database?

My Controller:

createNewPersonalData: function (req, res) {
var name = req.body.name,
    date_of_birth = req.body.date_of_birth;

var getAge = function () {
    var today = new Date();
            var dob = new Date(date_of_birth);
            var count = today.getFullYear() - dob.getFullYear();
            var m = today.getMonth() - dob.getMonth();
            if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
                count = count - 1;
            }

            return count;
        };
    PersonalInfo.create({
        name : name,
        date_of_birth : date_of_birth,
        age : getAge()
        }).then(data => {
           res.json({
                'status': 'OK',
                'messages': 'Personal Info Created',
                'data': data
            })
        });

but the response is only all attribute from the database table. There's no attribute/field age.

{
    "code": 200,
    "status": true,
    "data": {
        "id": 1,
        "name": "John",
        "date_of_birth": "1995-01-28T17:00:00.000Z",
    }
}

the response what I expected is like:

{
    "code": 200,
    "status": true,
    "data": {
        "id": 1,
        "name": "John",
        "date_of_birth": "1995-01-28T17:00:00.000Z",
        "age": 24
    }
}

How do I can add that age?

3
  • yes you can, can you also show what getAge() contains? Commented Jul 16, 2019 at 11:47
  • contain? that you mean the result? if that what you mean, the result is an int, like "42". It's come from curren_date - date_of_birth and convert into years Commented Jul 17, 2019 at 6:54
  • It is easy if you are using some kind of high level database frameworks. For example on mongoose you could use post middleware or virtual fields. Commented Jul 17, 2019 at 10:23

2 Answers 2

2

Just add the age property to the data object after converting it to a JSON object with the toJSON function in the Promise response.

PersonalInfo.create({
    name : name,
    date_of_birth : date_of_birth,
    //age : getAge()
}).then(data => {
    var info = data.toJSON({ versionKey:false });
    info['age'] = getAge();
    res.json({
      'code':200,
      'status': 'OK',
      'messages': 'Personal Info Created',
      'data': info
    })
});
Sign up to request clarification or add additional context in comments.

10 Comments

It's work in method post for create data, but how if we want to getAll data? The data response should be a list of array.
getAll data as in a list of all PersonalInfo ?
Yes, I mean how if I do method get to get All data, the result should be an array or list.
I've tried, but this didn't work. I think it because the Var Data Format. I've update the question with Var Data Format example added
@Blackjack There is type named VIRTUAL on sequelizejs. I think it is better to do calculation code in schema once, not in all other handlers. docs.sequelizejs.com/class/lib/data-types.js~VIRTUAL.html
|
2

Since you said using sequelize.js, you can use DataTypes.VIRTUAL on schema. And there is nothing you need to do in handlers for age calculation.

sequelize.define('PersonalInfo', {
  name: DataTypes.STRING,
  date_of_birth: DataTypes.DATE
  age: {
    type: DataTypes.VIRTUAL,
    get: function() {
      return getAge(this.get('date_of_birth'))
    }
  }
})

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.