sails
Version:
API-driven framework for building realtime apps, using MVC conventions (based on Express and Socket.io)
12 lines (7 loc) • 2.49 kB
Markdown
# `.toJSON()`
### Purpose
Whenever Waterline retrieves a record, it checks whether or not the record’s model has a [`customToJSON`](https://sailsjs.com/documentation/concepts/models-and-orm/model-settings#?customtojson) method defined; if so, Waterline adds the method to the record as its `toJSON` property. `toJSON` is _**not intended to be called directly in your code**_. Instead, it is used automatically when a record is serialized via a call to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior" target="_blank">`JSON.stringify()`</a>. The [`res.json()` method](https://sailsjs.com/documentation/reference/response-res/res-json), in particular, stringifies objects in this way.
When a [`customToJSON`](https://sailsjs.com/documentation/concepts/models-and-orm/model-settings#?customtojson) is defined for a model, the `.toJSON()` method will be added to records retrieved via [`.find()`](https://sailsjs.com/documentation/reference/waterline-orm/models/find), [`.findOne()`](https://sailsjs.com/documentation/reference/waterline-orm/models/find-one), [`.findOrCreate()`](https://sailsjs.com/documentation/reference/waterline-orm/models/find-or-create) and [`.stream()`](https://sailsjs.com/documentation/reference/waterline-orm/models/stream), as well as those retrieved by setting the [`fetch` meta key](https://sailsjs.com/documentation/reference/waterline-orm/queries/meta) to `true` in calls to [`.create()`](https://sailsjs.com/documentation/reference/waterline-orm/models/create), [`.createEach()`](https://sailsjs.com/documentation/reference/waterline-orm/models/create-each), [`.update()`](https://sailsjs.com/documentation/reference/waterline-orm/models/update) and [`.destroy()`](https://sailsjs.com/documentation/reference/waterline-orm/models/destroy). If any child records are attached via [`.populate()`](https://sailsjs.com/documentation/reference/waterline-orm/queries/populate), and the corresponding models have [`customToJSON`](https://sailsjs.com/documentation/concepts/models-and-orm/model-settings#?customtojson) methods, then the child records will also have `.toJSON()` functions attached.
See the [customToJSON documentation](https://sailsjs.com/documentation/concepts/models-and-orm/model-settings#?customtojson) for more info on how to customize the way your records are presented.
<docmeta name="displayName" value=".toJSON()">
<docmeta name="pageType" value="method">