JS functional object constructor - Neo4j Database has no method 'query' - javascript

I'm using the node-neo4j library along with node.js, underscore and prototype.
I'm trying to have a model which extends a database adapter. Code first.
BaseModel.js:
var _ = require("underscore"),
Neo4jAdapter = require('../adapters/neo4j/Adapter');
function BaseModel() {
_.extend(this, new Neo4jAdapter());
};
module.exports = BaseModel;
Neo4jAdapter.js:
var _ = require("underscore"),
Neo4j = require('neo4j');
function Neo4jAdapter() {
this.db = new Neo4j.GraphDatabase('http://localhost:3000');
};
Neo4jAdapter.prototype.insert = function(label, data, callback) {
console.log('Neo4jAdapter', 'Attempt to insert node');
if (label == '') throw 'Label is not defined';
var query = [
'CREATE (n:LABEL {mdata})',
'RETURN n'
].join('\n').replace('LABEL', label);
this.db.query(query, data, function (err, results) {
if (err) throw err;
console.log(results);
var result = results[0].n._data.data;
result.id = results[0].n._data.metadata.id;
callback(result);
});
};
module.exports = Neo4jAdapter;
The weird thing is the error I'm getting. I won't post all the node.js / express code here, but I'm hitting the insert function with an url. The response I get is the following:
Message: Object #
GraphDatabase has no method 'query'
Error: TypeError: Object #
GraphDatabase has no method 'query'
My question is: Why does the database object does not have the function query(), even tho the docs are saying it should have one?
Possible cause: I bet the adapter's db object is not populated yet when calling the insert method, but how do I do that?
Thanks

You have probably unintentionally installed the newer, alpha version.
See this issue for a similar problem: https://github.com/thingdom/node-neo4j/issues/150
Hi #Christopheraburns! Run this for me:
npm ls neo4j
I'm guessing you've installed node-neo4j v2 (we have
alpha versions in npm currently), which has breaking changes to the
API. The output of that npm ls will tell you if you have node-neo4j v1
or v2 installed (e.g. 1.1.1 vs. 2.0.0-alpha3).
You can downgrade to 1.1.1 by doing:
npm uninstall neo4j npm install neo4j#1.1.1 --save
Alternately, if
you're interested in v2 (still a WIP! but almost finished, and pretty
stable), here are some temporary links until this gets merged to
master:
API docs (WIP):
https://github.com/thingdom/node-neo4j/blob/v2/API_v2.md
Hope this helps! Feel free to re-open if this doesn't resolve things
for you.
So, you probably need to uninstall neo4j and reinstall the older version, or take a look at the cypher method in v2.
https://github.com/thingdom/node-neo4j/blob/v2/API_v2.md#cypher

Related

“TypeError: `level` is not a function” when using LevelJS 8.0.0

Currently, I am testing LevelDB as a key–value store for my Node.js projects, but I am having this issue: when I import Level and run the sample code from the website, leveljs.org, I get this error:
TypeError: level is not a function
at Object.<anonymous> (/home/runner/level/index.js:2:12)
at Module._compile (node:internal/modules/cjs/loader:1155:14)
I have searched for this error and nothing has came up. I have tried importing Level in different ways and none of them have worked. Here is my code, which is identical to the sample code on the website:
const level = require('level')
const db = level('./db', { valueEncoding: 'json' })
db.put('key', { example: true }, function (err) {
if (err) throw err
db.get('key', function (err, value) {
if (err) throw err
console.log(value)
})
})
When in doubt, always check the documentation at GitHub:
const { Level } = require('level')
// Create a database
const db = new Level('example', { valueEncoding: 'json' })
The README also has this note:
If you are upgrading: please see UPGRADING.md.
Version 8.0.0 (released 2022-03-25) states:
Changes to initialization
We started using classes, which means using new is now required. If you previously did:
const level = require('level')
const db = level('db')
You must now do:
const { Level } = require('level')
const db = new Level('db')
It also notes:
This release replaces leveldown and level-js with classic-level and browser-level.
The changelog lists this as a breaking change:
Breaking: switch to classic-level and browser-level (#215) (ad22b21) (Vincent Weevers).
The website is outdated (as of 2022-12-22, 22:09:03 UTC), and below the code sample it says:
As of level#5, the above code works in Node.js, Electron and browsers!
But you’re almost certainly using 8.0.0, not 5.0.0.
Shortly after bringing it up on the repository for leveljs.org, they fixed it.

How to use node-youtube-dl driver?

I use youtube-dl node driver to get information about videos on youtube, but I have trouble with ReferenceError - require is not defined (First line). I installed node-youtube-dl module on my laptop and the code is just taken from example in description. Is there anything else that I'm missing to do?
var youtubedl = require('youtube-dl');
var url = 'https://www.youtube.com/watch?v=9Q7Vr3yQYWQ';
ytdl.getInfo(url, function(err, info) {
if (err) throw err;
console.log('id:', info.id);
console.log('title:', info.title);
console.log('url:', info.url);
console.log('thumbnail:', info.thumbnail);
console.log('description:', info.description);
console.log('filename:', info._filename);
console.log('duration:', info.duration);
console.log('format_id:', info.format_id);
});
require() is a keyword in Node.js. It is used to import CommonJS modules like those in the npm registry. But it is not a keyword in your browser, where trying to use it will return a ReferenceError as you describe.
If you want to import npm modules using require() in your browser, you can try browserify or webpack. However, it is entirely possible (probable?) that youtube-dl is not compatible with browserify or webpack.
If you don't need to run it from a browser, you can put the code in a file (say, myFile.js) and run it from the command line with node:
node myFile.js
In your sample:
var youtubedl = require('youtube-dl');
However later you call it:
ytdl.getInfo(url, function(err, info)
just simply rename your require to ytdl, like this:
var ytdl = require('youtube-dl');

Node JS Error when copying file across partition. How to resolve this issue? [duplicate]

I'm trying to move a file from one partition to another in a Node.js script. When I used fs.renameSync I received Error: EXDEV, Cross-device link. I'd copy it over and delete the original, but I don't see a command to copy files either. How can this be done?
You need to copy and unlink when moving files across different partitions. Try this,
var fs = require('fs');
//var util = require('util');
var is = fs.createReadStream('source_file');
var os = fs.createWriteStream('destination_file');
is.pipe(os);
is.on('end',function() {
fs.unlinkSync('source_file');
});
/* node.js 0.6 and earlier you can use util.pump:
util.pump(is, os, function() {
fs.unlinkSync('source_file');
});
*/
I know this is already answered, but I ran across a similar problem and ended up with something along the lines of:
require('child_process').spawn('cp', ['-r', source, destination])
What this does is call the command cp ("copy"). Since we're stepping outside of Node.js, this command needs to be supported by your system.
I know it's not the most elegant, but it did what I needed :)
One more solution to the problem.
There's a package called fs.extra written by "coolaj86" on npm.
You use it like so:
npm install fs.extra
fs = require ('fs.extra');
fs.move ('foo.txt', 'bar.txt', function (err) {
if (err) { throw err; }
console.log ("Moved 'foo.txt' to 'bar.txt'");
});
I've read the source code for this thing. It attempts to do a standard fs.rename() then, if it fails, it does a copy and deletes the original using the same util.pump() that #chandru uses.
to import the module and save it to your package.json file
npm install mv --save
then use it like so:
var mv = require('mv');
mv('source_file', 'destination_file', function (err) {
if (err) {
throw err;
}
console.log('file moved successfully');
});
I made a Node.js module that just handles it for you. You don't have to think about whether it's going to be moved within the same partition or not. It's the fastest solution available, as it uses the recent fs.copyFile() Node.js API to copy the file when moving to a different partition/disk.
Just install move-file:
$ npm install move-file
Then use it like this:
const moveFile = require('move-file');
(async () => {
await moveFile(fromPath, toPath);
console.log('File moved');
})();

MongoClient TypeError

I am a NodeJS newbie and JS can-kicker trying out DI for the first time. Here are the questions I looked at before deciding to ask mine, since they show the same error: [1][2]
Running my entry point yields:
this.client = new MongoClient(server);
^
TypeError: undefined is not a function
Entry point
var config = require('./config.json');
var Providers = require('./providers');
var providers = new Providers(config.db);
console.log(providers);
./providers/index.js
Both AssetProvider and UserProvider suffer the same error. I think I only need to show one.
module.exports = function Provider(dbConfig)
{
var UserProvider = require('./userProvider');
var AssetProvider = require('./assetProvider');
this.users = new UserProvider (dbConfig.name, dbConfig.host, dbConfig.port);
this.assets = new AssetProvider(dbConfig.name, dbConfig.host, dbConfig.port);
}
./providers/userProvider.js
Problem line marked
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var Server = mongodb.Server;
var ObjectID = mongodb.ObjectID;
var UserProvider = function (database, host, port) {
var server = new Server(host, port, { auto_reconnect: true });
// Error is here
this.client = new MongoClient(server);
this.client.open(function (error, client) {
this.db = client.db(database);
});
};
// ...a bunch of prototype stuff...
// ...
module.exports = UserProvider;
From what I have read in other locations online, I don't see anything wrong with my syntax. I have tried the following declaration...
function UserProvider(database, host, port)
as opposed to
var UserProvider = function(database, host, port)
Everything else I did was comparable to slapping a car engine with a wrench. The truth is, I simply do not understand what is so wrong here, but I do know that I just want to make a composition of objects across files so that my entry point can readily use all providers through a single object.
JohnnyHK turned out to be correct about it being a version issue.
Oddly enough, the error did not go away when running npm update mongodb
However, it did go away when I ran npm install mongodb a second time.
No changes were made in the code, and mongodb was already inside the local
node_modules folder. Even so, I suspect this had to do with a discrepancy between an instance in node_modules and an instance in NODE_PATH.
I'm only speculating as to why exactly npm install solved the problem considering the latest version should have been installed. All I know is that the error is gone and the code is working.
Thank you for the comments!
I got exactly the same issue. After a quick research I realised that I have an old mongodb module version (0.9.x). After installing the latest (1.13.19) - the issue has been fixed.
npm install mongodb#1.3.13

How do I move file a to a different partition or device in Node.js?

I'm trying to move a file from one partition to another in a Node.js script. When I used fs.renameSync I received Error: EXDEV, Cross-device link. I'd copy it over and delete the original, but I don't see a command to copy files either. How can this be done?
You need to copy and unlink when moving files across different partitions. Try this,
var fs = require('fs');
//var util = require('util');
var is = fs.createReadStream('source_file');
var os = fs.createWriteStream('destination_file');
is.pipe(os);
is.on('end',function() {
fs.unlinkSync('source_file');
});
/* node.js 0.6 and earlier you can use util.pump:
util.pump(is, os, function() {
fs.unlinkSync('source_file');
});
*/
I know this is already answered, but I ran across a similar problem and ended up with something along the lines of:
require('child_process').spawn('cp', ['-r', source, destination])
What this does is call the command cp ("copy"). Since we're stepping outside of Node.js, this command needs to be supported by your system.
I know it's not the most elegant, but it did what I needed :)
One more solution to the problem.
There's a package called fs.extra written by "coolaj86" on npm.
You use it like so:
npm install fs.extra
fs = require ('fs.extra');
fs.move ('foo.txt', 'bar.txt', function (err) {
if (err) { throw err; }
console.log ("Moved 'foo.txt' to 'bar.txt'");
});
I've read the source code for this thing. It attempts to do a standard fs.rename() then, if it fails, it does a copy and deletes the original using the same util.pump() that #chandru uses.
to import the module and save it to your package.json file
npm install mv --save
then use it like so:
var mv = require('mv');
mv('source_file', 'destination_file', function (err) {
if (err) {
throw err;
}
console.log('file moved successfully');
});
I made a Node.js module that just handles it for you. You don't have to think about whether it's going to be moved within the same partition or not. It's the fastest solution available, as it uses the recent fs.copyFile() Node.js API to copy the file when moving to a different partition/disk.
Just install move-file:
$ npm install move-file
Then use it like this:
const moveFile = require('move-file');
(async () => {
await moveFile(fromPath, toPath);
console.log('File moved');
})();

Categories

Resources