MongoClient TypeError - javascript

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

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.

Requiring files in electron without babel

I'm trying to convert a web application into an electron app. I have multiple functions, in different files that I've imported into my main.js using a transpiler.
However, whenever I try do that in my electron app, I run into an issue with a module I'm using to move away from using php to access my database. Instead I'm using the mysql module on npm.
I want to save this function in its own file, and then require it in main.js. When I try to transpile it with babel, I get an error about Net.Connection not working (or something along those lines). As I understand it, this is because of how Node works. I'm happy to work around this, but I'm hoping there's a way to save this function in another file, and import it without having to use babel.
function loadColourFilter(){
var mysql = require('mysql');
let query_result;
var connection = mysql.createConnection({
host : 'xxxxxxxxxxxx',
user : 'xxxxxxxxxxxx',
password : 'xxxxxxxxxxxx',
database : 'xxxxxxxxxxxx'
});
connection.connect();
let query = "xxxxxxxxxxxxxxxx";
connection.query(query, function (error, results, fields) {
});
connection.end();
return (query_result);
}
EDIT: I've removed some parts of the function to keep credentials safe and whatnot. I'm fairly certain their absence won't change anything when trying to solve this.
EDIT:
My project directory is essentially
src
--- js
--- --- main.js
--- functionFile.js // This would be where my loadColourFilter function above would be saved
--- node_modules
--- --- ...
--- index.html // js/main.js is referenced in a script tag here.
--- main.js // Where the electron window is created.
--- package.json
There should be 2 js contexts, one running in the electron app and one running in node. You won't be able to require you scripts directly from your directory if you are in the electron context (which is like a browser js context).
I'm just assuming this is the case since we don't get a lot of information for your problem, and the other answer should have resolved your problem.
Try to include your js file in your index.html and see what's up.
Edit: Since it's a Transpiling error with babel, babel is probably transpiling for node when it should transpile for the browser.
You can easily make a simple local module using NodeJS by creating a source file and then adding a module.exports assignment to export some functionality/variables/etc from the file. In your case something like a file named colourFilter.js with the contents:
function load(){
var mysql = require('mysql');
let query_result;
var connection = mysql.createConnection({
host : 'xxxxxxxxxxxx',
user : 'xxxxxxxxxxxx',
password : 'xxxxxxxxxxxx',
database : 'xxxxxxxxxxxx'
});
connection.connect();
let query = "xxxxxxxxxxxxxxxx";
connection.query(query, function (error, results, fields) {
});
connection.end();
return (query_result);
}
module.exports = load
And then in your code where you'd like to use it include it by doing something like:
loadColourFilter = require('colourFilter.js')
And use the function like
let result = loadColourFilter()
This is a simple way to split up your code into multiple files/classes/modules but still keep one main file/class/module as the important one which is the public-facing portion or entry point. And of course you don't have to use the names I've used above :P
If you would like to make an object-style module you can instead export an object like
module.exports = {
load
}
Or
module.exports = {
load: loadFunctionNameInThisFile
}
And then use it like
const colourFilter = require('colourFilter.js')
let result = colourFilter.load()

nodeJS - socks.Agent is not a constructor

var fs = require('fs');
var socks = require('socks');
var proxies = fs.readFileSync('proxies.txt').replace(/\r/g, '').split('\n');
function createAgent() {
var proxy = proxies[Math.floor(Math.random() * proxies.length)];
return new socks.Agent({
ipaddress: proxy[0],
port: proxy[1],
type: 5
});
}
Socks module has changed the libraries and this script wont work anymore.
Can anybody help me and explain this ?
I didn't expect to see you here, I was having the same problem but then I read your question and you stated
Socks module has changed the libraries
That gave me the idea to install an older version of socks.
npm install socks#1
And that worked. It worked for me, it should work for you.

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');
})();

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

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

Categories

Resources