Home > database >  how can I get, fetched data from neo4j?
how can I get, fetched data from neo4j?

Time:07-31

I was trying to fetch data from neo4j database. Here is my function for getting data from database which I found on their official website and have modified it little bit:

function receiveDataFromDB() {
 var neo4j = require("neo4j-driver");
 var driver = neo4j.driver(
   "neo4j://localhost",
   neo4j.auth.basic("neo4j", "something")
 );

 console.log(driver);
 var session = driver.session({
   database: "neo4j",
   defaultAccessMode: neo4j.session.READ,
 });

 session.run(`match (n) return n`).subscribe({
   onKeys: (keys) => {
     console.log(keys);
   },
   onNext: (record) => {
     console.log(record.get("n"));
   },
   onCompleted: () => {
     session.close(); // returns a Promise
   },
   one rror: (error) => {
     console.log(error);
   },
 });
}

So this function only console.log-s it:

enter image description here

but I want it to use outside the function. I've tried returning return record.get("n") inside onNext but got errors instead.

CodePudding user response:

You can simply use the try-catch equivalent of your query, like this:

try { 
const result = session.run(`match (n) return n`);
} catch (error) {}
finally {
  session.close();
}

Or try setting your result in a variable, like this:

const result = [];
session.run(`match (n) return n`).subscribe({
   onKeys: (keys) => {
     console.log(keys);
   },
   onNext: (record) => {
     result.push(record.get("n"));
   },
   onCompleted: () => {
     session.close(); // returns a Promise
   },
   one rror: (error) => {
     console.log(error);
   },
 });
  • Related