Search code examples
memgraphdb

What is the easiest way to connect to Memgraph using Node.js?


I want to test the creation of an application that uses Node.js and Memgraph. What is the fastest and easiest way for me to test this type of setup?


Solution

  • The easiest way is to use Express.js. Here are the exact steps:

    1. Create a new directory for your application, /MyApp and position yourself in it.
    2. Create a package.json file using npm init
    3. Install Express.js using npm install express --save and the Bolt driver using npm install neo4j-driver --save in the /MyApp directory. Both packages will be added to the dependencies list.

    To make the actual program, create a program.js file with the following code:

    const express = require("express");
    const app = express();
    const port = 3000;
    var neo4j = require("neo4j-driver");
    
    app.get("/", async (req, res) => {
      const driver = neo4j.driver("bolt://localhost:7687");
      const session = driver.session();
    
      try {
        const result = await session.writeTransaction((tx) =>
          tx.run(
            'CREATE (a:Greeting) SET a.message = $message RETURN "Node " + id(a) + ": " + a.message',
            {
              message: "Hello, World!",
            }
          )
        );
    
        const singleRecord = result.records[0];
        const greeting = singleRecord.get(0);
    
        console.log(greeting);
      } finally {
        await session.close();
      }
    
      // on application exit:
      await driver.close();
    });
    
    app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`);
    });
    

    Once you save the file, you can run your program using node program.js.

    For additional details check the official Memgraph documentation.