### Installing Neogma with npm (Bash) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Getting-Started.md This snippet provides the command to install the Neogma library using the npm package manager. It's a prerequisite for using Neogma in your project. ```bash npm i neogma ``` -------------------------------- ### Installing Neogma with yarn (Bash) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Getting-Started.md This snippet provides the command to install the Neogma library using the yarn package manager. It's an alternative installation method to npm. ```bash yarn add neogma ``` -------------------------------- ### Accessing neo4jDriver exports (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Getting-Started.md This snippet shows how to access various components exported by `neo4jDriver`, which wraps the `neo4j-driver` package. It includes examples for a validator, a type constructor, and a TypeScript interface. ```js /* --> validator */ neo4jDriver.Date(); /* --> type contructor */ neo4jDriver.types.DateTime(); /* --> typescript interface */ neo4jDriver.Point; ``` -------------------------------- ### Installing codedoc Dependencies with npm Source: https://github.com/themetalfleece/neogma/blob/master/documentation/README.md This command installs all required Node.js packages and dependencies for the codedoc project. It must be run from the `.codedoc` directory to ensure all necessary tools for building and serving the documentation are available. ```Shell npm i ``` -------------------------------- ### Importing Neogma modules with require (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Getting-Started.md This snippet demonstrates how to import various Neogma classes and functions using the CommonJS `require` syntax in JavaScript, making them available for use in your application. ```js const { BindParam, ModelFactory, Neogma, QueryBuilder, QueryRunner, Where, Literal, getSession, Op, neo4jDriver } = require('neogma'); ``` -------------------------------- ### Initializing a Neogma instance (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Getting-Started.md This snippet demonstrates how to initialize a `Neogma` instance by providing connection details (URL, username, password) and optional configurations like a logger or encryption settings. This instance is fundamental for all subsequent database operations and model definitions. ```js const neogma = new Neogma( { url: 'bolt://localhost:7687', username: 'neo4j', password: 'password', /* --> (optional) the database to be used by default for sessions */ database: 'myDb', }, { /* --> (optional) logs every query that Neogma runs, using the given function */ logger: console.log, /* --> any driver configuration can be used */ encrypted: true, } ); ``` -------------------------------- ### Serving Documentation Locally with codedoc Source: https://github.com/themetalfleece/neogma/blob/master/documentation/README.md This command starts a local development server, allowing you to view the documentation in a web browser. It's useful for real-time previewing of changes during development, with the access URL displayed in the terminal. ```Shell codedoc serve ``` -------------------------------- ### Verifying Neogma connectivity (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Getting-Started.md This snippet shows how to use the `verifyConnectivity()` method on a Neogma instance to confirm a successful connection to the Neo4j database. A `NeogmaConnectivityError` is thrown if the connection fails. ```js await neogma.verifyConnectivity(); ``` -------------------------------- ### Importing Neogma modules with import (TypeScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Getting-Started.md This snippet illustrates how to import Neogma classes, functions, and specific types using the ES module `import` syntax in TypeScript, enabling type-safe development. ```ts import { BindParam, ModelFactory, Neogma, QueryBuilder, QueryRunner, Where, Literal, getSession, Op, neo4jDriver } from 'neogma'; // importing types import { /* --> used in Model definition */ ModelRelatedNodesI, NeogmaInstance, /* --> all possible neo4j types which can be used in Models */ Neo4jSupportedTypes } from 'neogma'; ``` -------------------------------- ### Accessing Neogma utility properties (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Getting-Started.md This snippet illustrates how to access various utility properties from an initialized Neogma instance, including the underlying Neo4j driver, the `QueryRunner` instance, a session getter, and a map of defined models by their names. ```js /* --> gets the neo4j driver */ const driver = neogma.driver; /* --> gets the QueryRunner instance used by this neogma instance */ const queryRunner = neogma.queryRunner; /* --> wrapper for getSession */ const getSession = neogma.getSession; // @see [Sessions](./Sessions) /* --> the defined Models by their names */ const modelsByName = neogma.modelsByName; // @see [Defining a Model](./Models/Defining-a-Model) ``` -------------------------------- ### Building Static Documentation Files with codedoc Source: https://github.com/themetalfleece/neogma/blob/master/documentation/README.md This command compiles the documentation source into static HTML, CSS, and JavaScript files. These generated files are suitable for deployment to any web server and are outputted into the `docs` and `assets` directories. ```Shell codedoc build ``` -------------------------------- ### Creating Neogma Instance from Record using buildFromRecord (JS) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Instances.md This snippet demonstrates the recommended way to create a Neogma instance from an existing node record obtained from a `QueryResult`. It uses the `buildFromRecord` static method, which correctly sets the instance's `labels` property. The example queries for a user, builds an instance, modifies a property, and saves the changes. ```js const result = await new QueryBuilder() // @see [QueryBuilder](../QueryBuilder/Overview) .match({ model: Users, where: { id: '1' }, identifier: 'u' }) .return ('u') .run(); const userRecord = result.records[0]?.get('u'); if (!userRecord) { throw new Error('user not found'); } const userInstance = Users.buildFromRecord(userRecord); console.log(userInstance.labels); // ["User"] userInstance.name = 'Some new name'; await userInstance.save(); /* --> the instance will be updated */ ``` -------------------------------- ### Creating Where Instance for Multiple Nodes (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Where-Parameters.md This example illustrates how to create a `Where` instance that includes conditions for multiple node identifiers (`n` and `o`). It demonstrates how the `getStatement('text')` method combines conditions for all specified identifiers and how `bindParam.get()` collects all bind parameters. ```JavaScript const where = new Where({ n: { x: 5, y: 'bar' }, o: { z: true, } }); console.log(where.getStatement('text')); // "n.x = $x AND n.y = $y AND o.z = $z" console.log(where.bindParam.get()); // { x: 5, y: 'bar', z: true } ``` -------------------------------- ### Creating New Session with getRunnable Helper in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Sessions-and-Transactions.md This example illustrates using the `getRunnable` helper when no existing session or transaction is provided. It automatically creates a new Neo4j session, allowing database queries to be executed within its scope, and requires a Neo4j driver and optional session parameters. ```JavaScript await getRunnable( /* --> no runnable is passed, so a new session will be created */ null, async (session) => { await queryRunner.run('RETURN 1 = 1', {}, session); }, /* --> a neo4j driver is needed */ driver, { /* --> pass any other params, as you would for the driver's `session` method */ database: "myDb" } ); ``` -------------------------------- ### Creating Neogma Instance from Data using build (JS) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Instances.md This snippet illustrates an alternative, less recommended method to create a Neogma instance for an existing node using the `build` static method. It requires passing the node's properties and explicitly setting the status to 'existing', but it does not automatically set the `labels` property. The example queries for a user, builds an instance, modifies a property, and saves the changes. ```js const result = await new QueryBuilder() // @see [QueryBuilder](../QueryBuilder/Overview) .match({ model: Users, where: { id: '1' }, identifier: 'u' }) .return ('u') .run(); const userData = result.records[0]?.get('u')?.properties; if (!userData) { throw new Error('user not found'); } const userInstance = Users.build(userData, { status: 'existing' }); userInstance.name = 'Some new name'; await userInstance.save(); /* --> the instance will be updated */ ``` -------------------------------- ### Using Existing BindParam with Where Instance (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Where-Parameters.md This example demonstrates how to initialize a `Where` instance using an existing `BindParam` instance. It highlights that if a key already exists in the provided `BindParam`, the `Where` instance will generate a new unique key for its own parameters (e.g., `x__aaaa`) and that the `Where` instance's `bindParam` property will reference the *same* mutated `BindParam` instance. ```JavaScript const existingBindParam = new BindParam({ x: 4, }); const where = new Where( { n: { /* --> the same key as in the bind param can be used */ x: 5, y: 'bar' } }, existingBindParam ); /* --> the "x" key already exists in the bind param, so a new one is used */ console.log(where.getStatement('text')); // "n.x = $x__aaaa AND n.y = $y" console.log(where.bindParam.get()); // { x: 4, x_aaaa: 5, y: 'bar' } console.log(where.bindParam === existingBindParam); // true ``` -------------------------------- ### Advanced Node and Relationship Creation with Neogma (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryBuilder/Create-Clause.md This advanced example demonstrates creating complex node and relationship patterns using `Model.getRelationshipByAlias` for predefined relationship configurations. It shows how to combine aliases with custom properties and directions to build intricate Cypher CREATE statements. ```JavaScript const queryBuilder = new QueryBuilder().create({ related: [ { identifier: 'a', model: ModelA, properties: { nodeProp: '20', }, }, /* --> The static `getRelationshipByAlias` of a model can be used as a shortcut. */ ModelA.getRelationshipByAlias('Relationship1'), { identifier: 'b' }, { direction: 'in' }, { ...ModelA.getRelationshipByAlias('Relationship2'), identifier: 'r2', properties: { relProp: 2 } }, {} ], }); /* --> assuming MyModel.getLabel() returns `MyModelLabel` */ /* --> assuming 'Relationship1' has configuration: direction: 'out', name: 'Relationship1Name' */ /* --> assuming 'Relationship1' has configuration: direction: 'in', name: 'Relationship2Name' */ // --> CREATE (a:`MyModelLabel` { nodeProp: $nodeProp })-[:Relationship1Name]->(b)<-[r2:Relationship2Name { relProp: $relProp }]-() console.log(queryBuilder.getStatement()); // --> { nodeProp: '20', relProp: 2 } console.log(queryBuilder.getBindParam().get()); ``` -------------------------------- ### Adding Parameters to Existing Where Instance (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Where-Parameters.md This example demonstrates how to dynamically add new parameters to an already initialized `Where` instance using the `addParams` method. It shows how the existing instance is mutated to include the new conditions and how unique bind parameter keys are generated if conflicts arise. ```JavaScript const where = new Where({ n: { x: 5, y: 'bar' } }); where.addParams({ n: { z: true }, o: { x: 4 } }); console.log(where.getStatement('text')); // "n.x = $x AND n.y = $y AND n.z = $z AND o.x = $x__aaaa" console.log(where.bindParam.get()); // { x: 5, y: 'bar', z: true, x__aaaa: 4 } ``` -------------------------------- ### Managing Sessions with Neogma getSession Helper (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Sessions-and-Transactions.md This example illustrates the use of the `getSession` helper for managing database sessions. It allows passing an existing session or creating a new one if none is provided. The helper automatically closes the session after the callback completes, and supports nested calls by ensuring the session closes only after all nested operations are done. It also shows how to pass additional session parameters like `database`. ```JavaScript await getSession( /* --> no session is passed, so a new one will be created */ null, async (session) => { /* --> this session can be used in more than one Neogma operations */ await Users.createOne( { id: '1', name: 'John' }, { session } ); /* --> let's create a function that takes a session param */ const myFindUser = (sessionParam) => { /* --> this param is used for a getSession. So, if it already exists, it will be used. Else, a new one will be created */ await getSession(sessionParam, async (sessionToUse) => { /* --> we can perform multiple operations with this session */ await Users.findAll({ session: sessionToUse }); await Users.findOne({ session: sessionToUse }); await queryRunner.run('RETURN 1 = 1', {}, sessionToUse); }, driver); }; /* --> no session is given, so the operations in 'myFindUser' will run in their own session */ await myFindUser(null); /* --> the existing session is given, so the operations in 'myFindUser' will run using this existing session */ await myFindUser(session); }, /* --> a neo4j driver is needed */ driver, { /* --> pass any other params, as you would for the driver's `session` method */ database: "myDb" } ); /* --> at this stage, the session will close */ ``` -------------------------------- ### Retrieving BindParam Values in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Bind-Parameters.md Shows how to use the `get()` method to retrieve the current object containing all bind parameters stored within a `BindParam` instance. This method returns the complete set of key-value pairs managed by the instance. ```JavaScript const bindParam = new BindParam({ x: 5, y: 'bar' }); console.log(bindParam.get()); // { x: 5, y: 'bar' } ``` -------------------------------- ### Using Neogma Model Helper Functions (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Defining-a-Model.md Showcases various helper functions provided by a Neogma Model for database operations and configuration retrieval. These functions allow getting relationship configurations, primary key fields, model names, and labels. ```JavaScript /* --> by providing an alias, gets the relationship configuration (model, direction, name, properties) */ Users.getRelationshipConfiguration('Orders'); // --> { model: Orders, direction: 'out', name: 'CREATES', properties: {...} } /* --> by providing an alias, gets the relationship information (model, direction, name). It's similar to getRelationshipConfiguration but it doesn't return "properties", so it's safe to use in QueryBuilder */ Users.getRelationshipByAlias('Orders'); // --> { model: Orders, direction: 'out', name: 'CREATES'} /* --> by providing an alias, reverses the configuration of the relationship, so it's perfectly duplicated when definition the same relationship at the other model (here Orders) */ Users.reverseRelationshipConfiguration('Orders'); // --> { model: Users, direction: 'in', name: 'CREATES', properties: {...} } /* --> gets the primaryKeyField provided when defining the Model */ Users.getPrimaryKeyField(); // --> id /* --> gets a name which is generated by the Model labels */ Users.getModelName(); // --> Users /* --> gets the labels of this model as provided in its definition */ AdminUsers.getRawLabels(); // --> ['Admin', 'User'] /* --> gets the labels of this model, to be used in a query. Wrapper for QueryRunner.getNormalizedLabels */ AdminUsers.getLabel(); // --> `Admin`:`User` /* --> getting a Model by its name by using the neogma instance */ neogma.modelsByName['Users']; ``` -------------------------------- ### Globally Configuring QueryBuilder's QueryRunner in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryBuilder/Overview.md This snippet demonstrates how to set the `QueryBuilder.queryRunner` static property globally. This configuration ensures that all subsequent `QueryBuilder` instances will use the specified `QueryRunner` by default, simplifying execution setup across an application. ```js QueryBuilder.queryRunner = new QueryRunner(...); ``` -------------------------------- ### Creating a Node with an Object in Neogma QueryBuilder (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryBuilder/Create-Clause.md This example illustrates creating a Neo4j node using an object configuration in Neogma's QueryBuilder. It specifies the node's identifier, label, and properties, demonstrating how Neogma automatically parameterizes properties for secure query generation. ```JavaScript const queryBuilder = new QueryBuilder().create({ /* --> (optional) the identifier of the node */ identifier: 'n', /* --> (optional) the label of the node */ label: 'MyLabel', /* --> (optional) the properties of thie node */ properties: { id: '20', }, }); console.log(queryBuilder.getStatement()); // CREATE (n:MyLabel { id: $id }) console.log(queryBuilder.getBindParam().get()); // { id: '20' } ``` -------------------------------- ### Creating Nodes with Nested Relationships in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/README.md This example illustrates how to create multiple nodes and establish relationships between them in a single operation using Neogma's `createMany` method. It demonstrates creating a `User` node and simultaneously creating or matching an `Order` node to associate with it, showcasing infinite nesting capabilities. ```JavaScript await Users.createMany([ { id: '1', name: 'John', age: 38, // assuming we're created an Orders Model and alias Orders: { attributes: [ { // creates a new Order node with the following properties, and associates it with John id: '1', status: 'confirmed', }, ], where: { params: { // matches an Order node with the following id and associates it with John id: '2', }, }, }, }, ]); // find the Order node which is created in the above operation const order = await Orders.findOne({ where: { id: '1', }, }); console.log(order.status); // confirmed ``` -------------------------------- ### Defining and Using beforeDelete Hook for User Nodes (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Hooks.md This snippet demonstrates how to implement a `beforeDelete` hook for `Users` nodes. This hook executes just before an instance is deleted, making it suitable for logging or performing cleanup actions. The example shows the hook logging a message to the console before the user node is removed from the database. ```JavaScript Users.beforeDelete = ( /* --> the Instance that's about to be deleted */ user ) => { console.log(`I'm ${user.name} and I'm being deleted :(`) } const user = Users.build({ id: '123', name: 'John', }); await user.save(); /* --> before the next command finished, beforeDelete runs and logs to the console */ await user.delete(); ``` -------------------------------- ### Creating a Single Node with Nested Relationships in Neogma (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Creating-Nodes-and-Relationships.md This example illustrates creating a single node and simultaneously establishing relationships with other nodes. It supports creating new related nodes via `properties` or linking to existing ones using `where` clauses, allowing for deeply nested relationship creation and property assignment on relationships. ```js const userWithOrder = await Users.createOne({ id: '1', name: 'Alex', /* --> associate with other nodes */ /* --> the Orders alias will be used, as defined in the Users model */ Orders: { /* --> (optional) create new nodes and associate with them */ properties: [ /* --> creates the following 2 Order nodes, and creates a relationship with each one of them using the configuration of the Orders alias */ { id: '2' }, { id: '3', items: 5, /* --> the relationship is created with the following property. It uses the alias (Rating) as defined in the Model. The actual property property will be that in the Model relationships definition */ Rating: 4, /* --> can create nodes and associate them with this Order node. The alias and configuration is that of the Orders model. This can be nested indefinitely */ /* --> the 'Critics' alias will be used, as defined in the 'Orders' model */ Critics: { properties: [{ id: '10' }] } } ], /* --> (optional) also associates the User node with existing Order nodes */ where: [ { /* --> the Where clause find matching the existing Nodes */ params: { // @see [Where](../Where-Parameters) id: '3' }, /* --> (optional) properties can be added to the relationship created by matching the User node with the existing Order nodes */ relationshipProperties: { Rating: 4, }, }, { /* --> another object can be used for matching the User node with the Order nodes of this where independently */ params: { items: 3, } } ] }, /* --> other aliases can be used here, to associate the User node with those of other Models */ }); console.log(userWithOrder.id); // "1" ``` -------------------------------- ### Creating Multiple Nodes in Neogma QueryBuilder (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryBuilder/Create-Clause.md This example demonstrates creating multiple Neo4j nodes in a single operation using the `multiple` attribute with an array of node configurations. Each entry in the array can specify an identifier, model, label, and properties, allowing for batch node creation. ```JavaScript const queryBuilder = new QueryBuilder().create({ multiple: [ /* --> each entry has the same type as creating with a single object, like in the examples above */ { identifier: 'a', model: ModelA, properties: { id: '20', }, }, { label: 'LabelB', }, ], }); /* --> assuming MyModel.getLabel() returns `MyModelLabel` */ console.log(queryBuilder.getStatement()); // CREATE (a:`MyModelLabel` { id: $id }), (:LabelB) console.log(queryBuilder.getBindParam().get()); // { id: '20' } ``` -------------------------------- ### Typing Fetched Relationship Properties (TypeScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Defining-a-Model.md Provides an example of how to correctly type relationship properties retrieved from a database query using the `ModelRelatedNodesI` interface, ensuring type safety for fetched data. ```TypeScript // let "queryResult" be the result of a raw query const relationshipProperties: UsersRelatedNodesI['Orders']['RelationshipProperties'] = queryResult.records[0].get('n').properties; ``` -------------------------------- ### Initializing QueryBuilder in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryBuilder/Overview.md This snippet demonstrates how to create a new `QueryBuilder` instance and chain methods like `match` and `return` to build a Cypher query. It also shows how to add additional parameters, such as a `limit`, at any point after initialization. ```js const queryBuilder = new QueryBuilder() .match({ identifier: 'p1' }) .return('p1'); /* --> additional parameters can be added at any point */ queryBuilder.limit(1); ``` -------------------------------- ### Getting Node Properties from QueryResult in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryRunner/Helpers.md This snippet demonstrates how to retrieve the properties of a node from a `QueryResult` object using `QueryRunner.getResultProperties`. It shows querying a User node by ID and then extracting its properties based on its alias 'n'. ```javascript const queryResult = await queryRunner.run( `MATCH (n:User {id: $id}) RETURN n`, { id: 1 }, ); /* --> get the properties of the node with the alias 'n' */ const properties = QueryRunner.getResultProperties(queryResult, 'n'); console.log(properties[0].id); // 1 ``` -------------------------------- ### Initializing Neogma with a Temporary Database (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Temporary-Databases.md This snippet demonstrates how to initialize a Neogma instance using an internally managed temporary database. It utilizes `Neogma.fromTempDatabase` and requires connection details such as URL, username, and password. A logger can also be configured for debugging purposes. ```javascript /* --> create a neogma instance that is latched onto an internally managed temp database */ const neogma = Neogma.fromTempDatabase( { /* --> use your connection details */ url: 'bolt://localhost', username: 'neo4j', password: 'password', }, { logger: console.log, } ); ``` -------------------------------- ### Getting Deleted Node Count from QueryResult in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryRunner/Helpers.md This snippet illustrates how to determine the number of nodes deleted by a `queryRunner.delete` operation using `QueryRunner.getNodesDeleted`. It performs a deletion based on a 'name' property and then logs the count of affected nodes. ```javascript const res = await queryRunner.delete({ where: { name: 'John' } }); const nodesDeleted = QueryRunner.getNodesDeleted(res); console.log(nodesDeleted); // 5 ``` -------------------------------- ### Initializing Neogma and Performing User CRUD Operations (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/index.md This snippet demonstrates how to initialize a Neogma instance, connect to a Neo4j database, define a `User` model with schema validation, and perform basic CRUD operations (create, update, save) on user nodes. It showcases model-based interactions and logging. ```JavaScript const { Neogma, ModelFactory } = require('neogma'); /* --> create a neogma instance and database connection */ const neogma = new Neogma( { /* --> use your connection details */ url: 'bolt://localhost', username: 'neo4j', password: 'password', }, { logger: console.log, } ); /* --> create a Users model */ const Users = ModelFactory({ label: 'User', schema: { name: { type: 'string', minLength: 3, required: true }, age: { type: 'number', minimum: 0, }, id: { type: 'string', required: true, } }, primaryKeyField: 'id', relationshipCreationKeys: {}, }, neogma); const createAndUpdateUser = async () => { /* --> creates a new Users node */ const user = await Users.createOne({ id: '1', name: 'John', age: 38 }); console.log(user.name); // 'John' user.name = 'Alex'; /* --> updates the node's name in the database */ await user.save(); console.log(user.name); // 'Alex' await neogma.getDriver().close(); } createAndUpdateUser(); ``` -------------------------------- ### Using Neogma Instance Wrappers for Session and Transaction Helpers in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Sessions-and-Transactions.md This snippet demonstrates the convenience of using `neogma` instance wrappers for `getSession`, `getTransaction`, and `getRunnable`. These wrappers automatically omit the driver parameter, simplifying calls for managing sessions and transactions directly through the Neogma instance. ```JavaScript await neogma.getSession(null, async (session) => { await Users.findOne({ session }); }); await neogma.getTransaction(null, async (transaction) => { await Users.findOne({ session: transaction }); }); await neogma.getRunnable(null, async (session) => { await Users.findOne({ session }); }); ``` -------------------------------- ### Validating a Neogma Instance - JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Instances.md This example demonstrates how to explicitly validate an instance's properties against its model schema using `instance.validate()`. It shows both a successful validation and how an invalid property value (e.g., negative age) will cause a `NeogmaInstanceValidationError` to be thrown. ```javascript user.age = 30; /* --> we can validate the properties of the Instance without saving it to the database. The properties of the Instance are valid, so this will not throw an error */ await user.validate(); try { user.age = -1; /* --> the properties of the Instance are invalid, so this will throw an error */ await user.validate(); } catch(err) { console.log(err); // NeogmaInstanceValidationError } ``` -------------------------------- ### Creating a QueryRunner Instance in Neogma (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryRunner/Overview.md This snippet demonstrates how to instantiate the `QueryRunner` class in Neogma. It requires a `driver` instance for database connection and optionally accepts a `logger` function for query logging and `sessionParams` for custom session configurations like specifying a database. The `sessionParams` will be ignored if a custom session is provided directly to a method. ```JavaScript const queryRunner = new QueryRunner({ /* --> a driver needs to be passed */ driver: neogma.driver, /* --> (optional) logs every query that this QueryRunner instance runs, using the given function */ logger: console.log, /* --> (optional) Session config to be used when creating a session to run any query. If a custom session is passed to any method, this param will be ignored. */ sessionParams: { database: 'myDb' } }); ``` -------------------------------- ### Updating a Neogma Instance - JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Instances.md This example shows how to modify properties of an existing Neogma instance and then save the changes to the database. Calling `instance.save()` on an already existing node triggers a MATCH-SET operation, updating only the changed properties. Validation can be optionally disabled. ```javascript /* --> given a user Instance, like the one created above, we can change the properties of the Instance */ user.name = 'Alex'; /* --> we reflect this change to the database. Since the node already exists in the databse, neogma will automatically run a MATCH-SET operation to update just the name of this node */ await user.save({ validate: false, }); ``` -------------------------------- ### Initializing Neogma and Managing User Nodes in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/README.md This snippet demonstrates how to initialize Neogma, define a `User` model with schema validation, and perform basic CRUD operations (create and update) on user nodes. It shows connecting to a Neo4j database, creating a new user, modifying its properties, and saving changes back to the database. ```JavaScript const { Neogma, ModelFactory } = require('neogma'); // create a neogma instance and database connection const neogma = new Neogma( { // use your connection details url: 'bolt://localhost', username: 'neo4j', password: 'password', }, { logger: console.log, }, ); // create a Users model const Users = ModelFactory( { label: 'User', schema: { name: { type: 'string', minLength: 3, required: true, }, age: { type: 'number', minimum: 0, }, id: { type: 'string', required: true, }, }, primaryKeyField: 'id', relationshipCreationKeys: {}, }, neogma, ); const createAndUpdateUser = async () => { // creates a new Users node const user = await Users.createOne({ id: '1', name: 'John', age: 38, }); console.log(user.name); // 'John' user.name = 'Alex'; // updates the node's name in the database await user.save(); console.log(user.name); // 'Alex' await neogma.getDriver().close(); }; createAndUpdateUser(); ``` -------------------------------- ### Initializing BindParam Instances in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Bind-Parameters.md Demonstrates various ways to create a `BindParam` instance: empty, with an initial object, or by merging multiple objects. It also illustrates that direct instantiation with non-unique keys will throw an error, emphasizing the need for unique name generation methods in such cases. ```JavaScript /* --> creating an empty BindParam instance */ const bindParam = new BindParam(); /* --> creating a BindParam instance with data (using an object) */ const bindParam = new BindParam({ x: 5, y: 'bar' }); /* --> creating a BindParam instance with data (using many objects) */ const bindParam = new BindParam( { x: 5, y: 'bar' }, { z: true } ); /* --> the following will throw an error since the keys are not unique. To add non-unique keys, the `getUniqueName` method must be used */ /* --> this is to prevent unexpected behavior in a case like the following: "n1.x = $x, n2.x = $x", where a different value is intended to be used each time */ const bindParam = new BindParam( { x: 5 }, { x: true // -> error! key 'x' is not unique } ); ``` -------------------------------- ### Using Existing Transaction with getRunnable Helper in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Sessions-and-Transactions.md This example illustrates how `getRunnable` can operate within an existing Neo4j transaction. It first creates a transaction using `getTransaction`, then passes this transaction to `getRunnable`, ensuring that all subsequent queries execute as part of the same atomic unit. ```JavaScript /* --> let's create a transaction */ await getTransaction( null, async (transaction) => { await queryRunner.run('RETURN 1 = 1', {}, transaction); await getRunnable( /* --> a transaction is passed, so it will be used */ transaction, async (transactionToUse) => { /* --> this runs in the same transaction as the other query */ await queryRunner.run('RETURN 1 = 1', {}, transactionToUse); }, driver ); }, driver ); ``` -------------------------------- ### Running Neogma Unit Tests - Yarn Source: https://github.com/themetalfleece/neogma/blob/master/README.md This command executes the unit tests for Neogma using Jest. Ensure a .env file with Neo4j connection strings is configured according to .env.example before running the tests. ```Shell yarn test ``` -------------------------------- ### Creating and Saving a Neogma Instance - JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Instances.md This snippet demonstrates how to create a new Neogma instance using `Model.build()` and then persist it to the database using `instance.save()`. The `save()` method performs a CREATE operation, and it supports optional parameters for validation and session management. ```javascript /* --> creates an Instance of the Users model, which still doesn't exist in the database */ const user = Users.build({ id: '1', name: 'John', age: 38, }); /* --> the Instance can be saved to the database. This will run a CREATE operation to create a node to match the Users Model configuration (label etc.) */ await user.save({ /* --> (optional, default true) validates that the properties of the Instance are valid, given the schema of the Model definition */ validate: true, /* --> (optional) an existing session or transaction to use */ session: null, }); ``` -------------------------------- ### Applying Object-Based Conditions in Neogma QueryBuilder (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryBuilder/Where-Clause.md This example illustrates defining WHERE conditions using a JavaScript object, specifically of type 'WhereParamsByIdentifierI'. The QueryBuilder automatically converts object properties into parameterized conditions, generating unique bind parameter names and values. ```js const queryBuilder = new QueryBuilder().where({ identifier1: { id: '20' }, identifier2: { id: '21', age: 28 } }); console.log(queryBuilder.getStatement()); // WHERE identifier1.id = $id AND identifier2.id = $id__aaaa AND identifier2.age = $age console.log(queryBuilder.getBindParam().get()); // { id: '20', id__aaaa: '21', age: 28 } ``` -------------------------------- ### Creating and Using Sessions with Neogma Driver (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Sessions-and-Transactions.md This snippet demonstrates how to obtain a session directly from the Neogma driver. The acquired session can then be reused across multiple Neogma operations, including Model queries (e.g., `createOne`, `findAll`) and QueryRunner executions. It also shows how to explicitly close the session after use. ```JavaScript /* --> the driver can be obtained by the Neogma instance */ const driver = neogma.getDriver(); /* --> use the driver to create a session */ const session = driver.session(); /* --> this session can be used in more than one Neogma operations */ await Users.createOne( { id: '1', name: 'John' }, { session } ); await Users.findAll({ session }); /* --> the session can also be used in the QueryRunner. Let 'queryRunner' be a QueryRunner instance */ await queryRunner.run('RETURN 1 = 1', {}, session); // @see [QueryRunner](./QueryRunner/Overview) /* --> closing the session */ await session.close(); ``` -------------------------------- ### Deleting Nodes/Relationships with Literal Object (Detach) in Neogma QueryBuilder (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryBuilder/Delete-Clause.md This example illustrates deleting nodes or relationships using a literal object, which allows for the optional `detach` parameter. Setting `detach: true` performs a `DETACH DELETE`, removing nodes along with their relationships. ```JavaScript const queryBuilder = new QueryBuilder().delete({ /* --> literal string to use */ literal: 'a, b', /* --> (optional) whether this delete will be "detach" */ detach: true }); console.log(queryBuilder.getStatement()); // DETACH DELETE a, b console.log(queryBuilder.getBindParam().get()); // {} ``` -------------------------------- ### Defining beforeSave Hook for Order Nodes with Related Creation (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Hooks.md This example illustrates the use of a `beforeSave` hook (which applies to `beforeCreate` for related nodes) on `Orders` nodes. It ensures that the 'items' property is non-negative before an order is saved, even when created as a related node through a `Users.createOne` operation. ```JavaScript Orders.beforeSave = (order) => { if (order.items < 0) { order.items = 0; } }; await Users.createOne({ id: '123', name: 'John', Orders: { properties: [ { id: '456', items: -1 } ] } }); /* --> the created Order node will have items === 0 */ ``` -------------------------------- ### Running QueryBuilder Instance in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryBuilder/Overview.md This snippet shows the simplest way to execute a Cypher query built with `QueryBuilder` when a `Neogma` instance is already defined. It uses the `raw` method for a direct Cypher string and then calls `run` to execute it. ```js await new QueryBuilder() .raw('match n return n') .run(); ``` -------------------------------- ### Acquiring and Reusing Where Instances in Neogma (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Where-Parameters.md This snippet demonstrates the `Where.acquire` static method, which ensures a `Where` instance is available. It shows how to acquire a new instance, reuse an existing one, create an instance from plain parameters, and pass an existing `bindParam` instance for parameter management. ```javascript const whereFirst = Where.acquire(null); console.log(whereFirst instanceof Where); // true const whereSecond = Where.acquire(whereFirst); console.log(whereFirst === whereSecond); // true /* --> an object with where parameters can be used */ const whereWithPlainParams = Where.acquire({ n: { x: 5 } }); console.log(whereWithPlainParams instanceof Where); // true /* --> a BindParam instance can be passed to be used */ const existingBindParam = new BindParam({ x: 4 }); const whereWithBindParams = Where.acquire( { n: { x: 5 } }, existingBindParam ); console.log(whereWithBindParams instanceof Where); // true console.log(whereWithBindParams.statement); // "n.x = $x__aaaa" console.log(whereWithBindParams.bindParam.get()); // { x: 4, x__aaaa: 5 } ``` -------------------------------- ### Building Neogma Tests - Yarn Source: https://github.com/themetalfleece/neogma/blob/master/README.md This command builds the test files for the Neogma project. It's a prerequisite before running unit tests and compiles the necessary test assets. ```Shell yarn build-tests ``` -------------------------------- ### Acquiring or Creating a BindParam Instance in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Bind-Parameters.md Illustrates the static `acquire()` method, which ensures a `BindParam` instance is available. If an existing instance is passed as an argument, it is returned as is; otherwise, a new `BindParam` instance is created and returned. This is useful for functions that might receive an optional `BindParam` instance. ```JavaScript const bindParamFirst = BindParam.acquire(null); console.log(bindParamFirst instanceof BindParam); // true const bindParamSecond = BindParam.acquire(bindParamFirst); console.log(bindParamFirst === bindParamSecond); // true ``` -------------------------------- ### Cypher for Creating Nodes with Relationships Source: https://github.com/themetalfleece/neogma/blob/master/README.md This Cypher query demonstrates how Neogma handles the creation of multiple nodes and their relationships in a single statement. It creates a `User` node, an `Order` node, and then establishes a `CREATES` relationship between them, also showing how to match an existing node for relationship creation. ```SQL Statement: CREATE (node:`User`) SET node += $data CREATE (node__aaaa:`Order`) SET node__aaaa += $data__aaaa CREATE (node)-[:CREATES]->(node__aaaa) WITH DISTINCT node MATCH (targetNode:`Order`) WHERE targetNode.id = $id CREATE (node)-[r:CREATES]->(targetNode) Parameters: { data: { name: 'John', age: 38, id: '1' }, data__aaaa: { id: '1', status: 'confirmed' }, id: '2' } ``` -------------------------------- ### Running QueryBuilder with Custom QueryRunner and Session in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryBuilder/Overview.md This snippet shows how to execute a `QueryBuilder` query by providing both a custom `QueryRunner` instance and an existing session. This allows for precise control over both the execution mechanism and the transactional context of the query. ```js /** let 'queryRunner' be a QueryRunner instance and 'session' be a Session/Transaction */ await new QueryBuilder() .raw('match n return n') .run(queryRunner, session); ``` -------------------------------- ### Using Where Statement in Cypher Query (Object Form, JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Where-Parameters.md This example demonstrates using the 'object' form of a `Where` statement, which is suitable for direct property matching within a node pattern (e.g., `(n {x: $x})`). It shows how `getStatement('object')` provides a property map and `bindParam.get()` provides the values, typically used for a single identifier. ```JavaScript const where = new Where({ n: { x: 5, y: 'bar' }, }); const objectStatement = where.getStatement('object'); // { x: $x, y: $y } const bindParamProperties = where.bindParam.get(); // { x: 5, y: 'bar' } await queryRunner.run( `MATCH (n ${objectStatement}) RETURN n`, bindParamProperties ); ``` -------------------------------- ### Creating Relationships via Instance Method in Neogma (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Creating-Nodes-and-Relationships.md This snippet illustrates how to create relationships using the `relateTo` method on a Neogma Model instance. The source node is implicitly the instance itself, so `where` parameters are only needed for the target nodes. Relationship properties and session management are also supported. ```JavaScript /* --> let 'user' be a Users instance */ await user.relateTo( { /* --> the alias of the relationship, as provided in the Model definition */ alias: 'Orders', /* --> where parameters for target node(s) */ where: { id: '2' }, /* --> properties of the relationship to be created */ properties: { /* --> use the key defined in the model and assign a value */ Rating: 4 }, /* --> (optional) throws an error if the created relationships are not equal to this number */ assertCreatedRelationships: 2, /* --> (optional) an existing session or transaction to use */ session: null } ); ``` -------------------------------- ### Defining and Using beforeCreate Hook for User Nodes (JavaScript) Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/Models/Hooks.md This snippet demonstrates how to define a `beforeCreate` hook for `Users` nodes. The hook runs before validation and node creation, allowing for data mutation, such as incrementing the 'age' property. It shows the hook's effect when creating a single user instance. ```JavaScript Users.beforeCreate = ( /* --> the Instance that's about to be saved to the database */ user ) => { if (user.age) { user.age += 2; } }; const user = await Users.createOne({ id: '123', name: 'John', age: -1 }); console.log(user.age); // 1 ``` -------------------------------- ### Merging Node with Neogma QueryBuilder in JavaScript Source: https://github.com/themetalfleece/neogma/blob/master/documentation/md/docs/QueryBuilder/Create-Clause.md This snippet illustrates how to use the `merge` method of the Neogma `QueryBuilder` to define a node to be merged. It specifies an identifier ('n'), a label ('MyLabel'), and properties (id: '20'). The example then shows how to retrieve the generated Cypher statement and its corresponding bind parameters, which are essential for executing the query against a Neo4j database. ```JavaScript const queryBuilder = new QueryBuilder().merge({ identifier: 'n', label: 'MyLabel', properties: { id: '20', }, }); console.log(queryBuilder.getStatement()); // MERGE (n:MyLabel { id: $id }) console.log(queryBuilder.getBindParam().get()); // { id: '20' } ``` -------------------------------- ### Formatting Neogma Code - Yarn Source: https://github.com/themetalfleece/neogma/blob/master/README.md This command applies Prettier to automatically format the Neogma codebase. It ensures consistent code style and readability throughout the project by adhering to predefined formatting rules. ```Shell yarn format ```