Skip to content

Commit

Permalink
docs(getters-setters): explain that getters do not run by default on …
Browse files Browse the repository at this point in the history
…`toJSON()`

Fix #13049
  • Loading branch information
vkarpov15 committed Feb 20, 2023
1 parent 10a7708 commit 2f86a87
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
20 changes: 15 additions & 5 deletions docs/tutorials/getters-setters.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,37 @@ Keep in mind that getters do **not** impact the underlying data stored in
MongoDB. If you save `user`, the `email` property will be 'ab@gmail.com' in
the database.

By default, Mongoose executes getters when converting a document to JSON,
including [Express' `res.json()` function](http://expressjs.com/en/4x/api.html#res.json).
By default, Mongoose does **not** execute getters when converting a document to JSON, including [Express' `res.json()` function](http://expressjs.com/en/4x/api.html#res.json).

```javascript
app.get(function(req, res) {
return User.findOne().
// The `email` getter will run here
// The `email` getter will NOT run here
then(doc => res.json(doc)).
catch(err => res.status(500).json({ message: err.message }));
});
```

To disable running getters when converting a document to JSON, set the [`toJSON.getters` option to `false` in your schema](../guide.html#toJSON) as shown below.
To run getters when converting a document to JSON, set the [`toJSON.getters` option to `true` in your schema](../guide.html#toJSON) as shown below.

```javascript
const userSchema = new Schema({
email: {
type: String,
get: obfuscate
}
}, { toJSON: { getters: false } });
}, { toJSON: { getters: true } });

// Or, globally
mongoose.set('toJSON', { getters: true });

// Or, on a one-off basis
app.get(function(req, res) {
return User.findOne().
// The `email` getter will run here
then(doc => res.json(doc.toJSON({ getters: true }))).
catch(err => res.status(500).json({ message: err.message }));
});
```

To skip getters on a one-off basis, use [`user.get()` with the `getters` option set to `false`](../api/document.html#document_Document-get) as shown below.
Expand Down
1 change: 1 addition & 0 deletions test/docs/getters-setters.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ describe('getters/setters', function() {
user.email; // **@gmail.com
// acquit:ignore:start
assert.equal(user.email, '**@gmail.com');
assert.equal(user.toJSON().email, 'ab@gmail.com');

user.email = 'test42@gmail.com';
assert.equal(user.email, 'te****@gmail.com');
Expand Down

0 comments on commit 2f86a87

Please sign in to comment.