.toJSON()

Purpose

This method also returns a cloned model instance. This one however includes all instance methods. Be sure to read the notes on this one.

Overview

Return Value

Description Possible Data Types
Cloned Record { }

Example Usage

  1. User.find().exec(
  2. function(err,myRecord){
  3. var datUser = myRecord.pop().toObject();
  4. console.log(datUser);
  5. });
  6. /* { id: 2,
  7. createdAt: '2013-10-31T22:42:25.459Z',
  8. updatedAt: '2013-11-01T20:12:55.534Z',
  9. name: 'Hank',
  10. phoneNumber: '101-150-1337' } */
  11. User.find().exec(
  12. function(err,myRecord){
  13. var datUser = myRecord.pop().toJSON();
  14. console.log(datUser);
  15. });
  16. /* { id: 2,
  17. createdAt: '2013-10-31T22:42:25.459Z',
  18. updatedAt: '2013-11-01T20:12:55.534Z',
  19. name: 'Hank' } */
  20. // Don't forget to handle your errors

For model

  1. module.exports = {
  2. attributes: {
  3. name: 'string',
  4. phoneNumber: 'string',
  5. // Override the default toJSON method
  6. toJSON: function() {
  7. var obj = this.toObject();
  8. delete obj.phoneNumber;
  9. return obj;
  10. }
  11. }
  12. }

Notes

The real power of toJSON relies on the fact every model instance sent out via res.json is first passed through toJSON. Instead of writing custom code for every controller action that uses a particular model (including the “out of the box” blueprints), you can manipulate outgoing records by simply overriding the default toJSON function in your model.
You would use this to keep private data like email addresses and passwords from being sent back to every client.

This is an instance method. Currently, instance methods ARE NOT TRANSACTIONAL. Because of this, it is recommended that you use the equivalent model method instead.