Overview Defining a Model Instances Creating Nodes and Relationships Merging Nodes and Relationships Updating Nodes and Relationships Deleting Nodes Deleting Relationships Finding Nodes and Relationships Hooks Temporary Databases
The beforeCreate
hook runs before a Node is created by the createOne
, createMany
statics, and the build
method.
It runs before the node is validated, therefore it's suitable for mutating data before the validation runs.
1linkUsers.beforeCreate = (
2link /* --> the Instance that's about to be saved to the database */
3link user
4link) => {
5link if (user.age) {
6link user.age += 2;
7link }
8link};
9link
10linkconst user = await Users.createOne({
11link id: '123',
12link name: 'John',
13link age: -1
14link});
15link
16linkconsole.log(user.age); // 1
It also runs when creating relating nodes
1linkOrders.beforeSave = (order) => {
2link if (order.items < 0) {
3link order.items = 0;
4link }
5link};
6link
7linkawait Users.createOne({
8link id: '123',
9link name: 'John',
10link Orders: {
11link properties: [
12link {
13link id: '456',
14link items: -1
15link }
16link ]
17link }
18link});
19link
20link/* --> the created Order node will have items === 0 */
The beforeDelete
hook runs before an Instance is deleted with its delete
method.
1linkUsers.beforeDelete = (
2link /* --> the Instance that's about to be deleted */
3link user
4link) => {
5link console.log(`I'm ${user.name} and I'm being deleted :(`)
6link}
7link
8linkconst user = Users.build({
9link id: '123',
10link name: 'John',
11link});
12link
13linkawait user.save();
14link
15link/* --> before the next command finished, beforeDelete runs and logs to the console */
16linkawait user.delete();