No AuthProvider for DEFAULT defined with mongoose 6 - node.js

When updating to Mongoose 6 with Mongodb nodejs driver version 4, I have the error below:
MongoInvalidArgumentError: No AuthProvider for DEFAULT defined.
at prepareHandshakeDocument (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:153:29)
at performInitialHandshake (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:63:5)
at /home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:25:9
at callback (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:244:9)
at Socket.connectHandler (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:282:9)
at Object.onceWrapper (events.js:519:28)
at Socket.emit (events.js:400:28)
at Socket.emit (domain.js:470:12)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1134:10)
From previous event:
at NativeConnection.Connection.openUri (/home/arch/git/project/node_modules/mongoose/lib/connection.js:778:19)
at /home/arch/git/project/node_modules/mongoose/lib/index.js:330:10
at promiseOrCallback (/home/arch/git/project/node_modules/mongoose/lib/helpers/promiseOrCallback.js:10:12)
at Mongoose._promiseOrCallback (/home/arch/git/project/node_modules/mongoose/lib/index.js:1151:10)
at Mongoose.connect (/home/arch/git/project/node_modules/mongoose/lib/index.js:329:20)
at connectToDb (/home/arch/git/project/core/configs/database.js:101:8)
at createServer (/home/arch/git/project/app.js:65:16)
at Object.<anonymous> (/home/arch/git/project/app.js:262:3)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
I don't have any authentication set up (this is my local development environment) so I don't understand where is the issue comming from. Here is the relevant connection code:
let connectionURL = 'mongodb://';
const connectionOptions = {
authSource: options.authSource,
};
if (options.user && options.password) {
connectionURL += `${options.user}:${options.password}#`;
}
connectionURL += `${options.host}/${dbName}?authSource=${options.authSource}`;
mongoose
.connect(connectionURL, connectionOptions, function onConnected(err) {
if (err) {
return cb(new Error(`Can not connect to database ${dbName}`));
}
return cb(null, mongoose.connection);
});

For a passwordless/userless connection, making sure the connection url doesn't contain authSource worked for me. This worked somehow before the version 4 of the driver, but not any more.
Also, either choose wether to pass options in the object or in the connection string. As the doc says:
Best practice is to put options that likely differ between development and production, like replicaSet or ssl, in the connection string, and options that should remain constant, like connectTimeoutMS or poolSize, in the options object
const connectionOptions = {};
if (options.user && options.password) {
connectionOptions.user = options.user;
connectionOptions.password = options.password;
connectionOptions.authSource = options.authSource;
}
const connectionURL = `mongodb://${options.host}/${dbName}`;
mongoose
.connect(connectionURL, connectionOptions, function onConnected(err) {
if (err) {
return cb(new Error(`Can not connect to database ${dbName}`));
}
return cb(null, mongoose.connection);
});
};

Related

importing mongodb results in error that is not related to mongodb when running the script using node command

I have a stand alone script that I am using to create an admin user. There will always be only one admin user. However, when I run the standalone script using node command in my nextjs project, I get this weird error below
node indexUser.js
/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/utils.js:50
var AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf( /*#__PURE__*/_wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
^
TypeError: Cannot convert undefined or null to object
at Function.getPrototypeOf (<anonymous>)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/utils.js:34:39)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/URL.js:4:15)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/webidl2js-wrapper.js:3:13)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/index.js:3:34)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (../src/index.ts:1:1)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (../src/connection_string.ts:3:1)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
Node.js v19.3.0
The script I am running has the below code:
import bcrypt from 'bcryptjs';
import MongoClientConnection from '../db';
import readline from 'readline';
import { logger } from '../logger';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter username: ', (username) => {
rl.question('Enter email: ', (email) => {
rl.question('Enter password: ', async (password) => {
const hashedPassword = await bcrypt.hash(password, 10);
const adminUserData = { username, email, hashedPassword };
try {
const db = await MongoClientConnection.Get();
const res = await db.insert(adminUserData);
} catch (e) {
logger.error(e);
}
rl.close();
});
});
});
In the code above, when I remove import MongoClientConnection from '../db'; the script works fine so, I believe the error is because of mongodb. I am using singleton connection for mongodb and have the below code for that
import { MongoClient } from 'mongodb';
const MongoClientConnection = (() => {
let db = null;
let instance = 0;
const DbConnect = async () => {
try {
let url = process.env.DB_URL;
let mongoClient = await MongoClient.connect(url, {
useUnifiedTopology: true,
});
const mongoDbInstance = mongoClient.db(process.env.DB);
return mongoDbInstance;
} catch (e) {
return e;
}
};
const Get = async () => {
try {
instance++; // this is just to count how many times our singleton is called.
console.log(`DbConnection called ${instance} times`);
if (db != null) {
console.log(`db connection is already alive`);
return db;
} else {
console.log(`getting new db connection`);
db = await DbConnect();
return db;
}
} catch (e) {
return e;
}
};
return {
Get: Get,
};
})();
export default MongoClientConnection;
Cannot really find any solution to this.

TypeError: Cannot read properties of undefined (reading 'getBalance') in node.js

I am getting error when using web3.js to get the balance of an account. I am using ganache. My code is below,
var Web3 = require("web3");
//connect with ganache
const ganacheWeb3 = new Web3(
new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545")
);
console.log(ganacheWeb3);
//check the balance of an account
const balanceOfAccount = Web3.Eth.getBalance(
"0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5"
);
console.log(
balanceOfAccount.then((result) =>
console.log(Web3.utils.fromWei(result, "ether"))
)
);
Web3.eth.getBalance(
"0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5",
(error, result) => {
if (error) {
console.log(error);
} else {
console.log(result);
}
}
);
I have used the normal functional way and callback way. I don't know which one is correct. But still I am getting error. The error is,
const balanceOfAccount = Web3.Eth.getBalance(
^
TypeError: Cannot read properties of undefined (reading 'getBalance')
at Object.<anonymous> (D:\Blockchain Development\Web3.js\intro-to-web3.js\index.js:10:35)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
at node:internal/main/run_main_module:23:47
I am trying to get the value of an ethereum account. But getting an error.
Change Web3.Eth.getBalance(...) to Web3.eth.getBalance(...).
Documentation: https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#getbalance

Unexpected token ')' Nodejs with Couchdb

I am using nodejs 14 and couchdb database 3.1.1
I am trying to connect and display list of couchdb databases using nodejs but following error occur
const NodeCouchDb = require('node-couchdb');`
const couch = new NodeCouchDb();
// node-couchdb instance with Memcached
const MemcacheNode = require('node-couchdb-plugin-memcached');
const couchWithMemcache = new NodeCouchDb({
cache: new MemcacheNode
});
// node-couchdb instance talking to external service
const couchExternal = new NodeCouchDb({
host: 'couchdb.external.service',
protocol: 'https',
port: 5984
});
// not admin party
const couchAuth = new NodeCouchDb({
auth: {
user: 'admin',
pass: 'godhelp'
}
});
couch.listDatabases()
.then(
dbs => dbs.map(...),
err => {
// request error occured
});
ERROR After Compiled :
dbs => dbs.map(...),
^
SyntaxError: Unexpected token ')'
at wrapSafe (internal/modules/cjs/loader.js:988:16)
at Module._compile (internal/modules/cjs/loader.js:1036:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
I think there is a syntax error in your code, but more fundamentally node-couchdb seems to be an inactive library that has not been updated in more than four years. I would recommend using nano, which is the official Apache CouchDB NodeJS library.
Here's a simple NodeJS script (index.js) using nano to list your databases.
const nano = require('nano')(process.env.COUCH_URL)
const main = async function() {
const response = await nano.db.list()
console.log(response)
}
main ()
You will need to create an environment variable called COUCH_URL:
export COUCH_URL="http://user:password#localhost:5984"
and then run the script:
node index.js
#[ 'deeds' ]

Handshake inactivity timeout error AWS node.js

i'm quite new with node.js. usually i'm connect the AWS through java but this time i needed to change from java based to node.js with lambda service. i have simple connection from node.js to AWS RDS Database,
var mysql = require('mysql');
var config = require('./config.json');
var pool = mysql.createPool({
host: config.dbhost,
user: config.dbuser,
password: config.dbpassword,
database: config.dbname,
});
pool.getConnection(function(err, connection) {
// Use the connection
if (err) {
console.log(err);
} else {
connection.query('Select 1+1 as numberss', function (error, results, fields) {
// And done with the connection.
connection.release();
// Handle error after the release.
if (error) throw error;
else console.log(results);
process.exit();
// Don't use the connection here, it has been returned to the pool
});
}
});
i've tried so many ways that i'm search in internet like adding timeout, check host information and etc.
but it's seem to return
{ Error: Handshake inactivity timeout
at Handshake.<anonymous> (/Users/HAUZDevTeam/HAUZ-HQ-Lambda/node_modules/mysql/lib/protocol/Protocol.js:160:17)
at Handshake.emit (events.js:189:13)
at Handshake._onTimeout (/Users/HAUZDevTeam/HAUZ-HQ-Lambda/node_modules/mysql/lib/protocol/sequences/Sequence.js:124:8)
at Timer._onTimeout (/Users/HAUZDevTeam/HAUZ-HQ-Lambda/node_modules/mysql/lib/protocol/Timer.js:32:23)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)
--------------------
at Protocol._enqueue (/Users/HAUZDevTeam/HAUZ-HQ-Lambda/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/Users/HAUZDevTeam/HAUZ-HQ-Lambda/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at PoolConnection.connect (/Users/HAUZDevTeam/HAUZ-HQ-Lambda/node_modules/mysql/lib/Connection.js:116:18)
at Pool.getConnection (/Users/HAUZDevTeam/HAUZ-HQ-Lambda/node_modules/mysql/lib/Pool.js:48:16)
at Object.<anonymous> (/Users/HAUZDevTeam/HAUZ-HQ-Lambda/local.js:9:6)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
code: 'PROTOCOL_SEQUENCE_TIMEOUT',
fatal: true,
timeout: 10000 }
is there any way to overcome this error or is there any wrong thing that i did on my code?

Mongodb Connect error: Just cant connect to the database

This is my code 👇
const mongoose = require("mongoose");
mongoose.connect("mongodb:://localhost:27017/crudwithnode", {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log("MongoDB Connected..."))
.catch((err) => console.log(err));
And this is the error I got 👇
MongoParseError: Invalid connection string
at parseConnectionString (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongodb\lib\core\uri_parser.js:547:21)
at connect (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongodb\lib\operations\connect.js:272:3)
at D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongodb\lib\mongo_client.js:215:5
at maybePromise (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongodb\lib\utils.js:719:3)
at MongoClient.connect (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongodb\lib\mongo_client.js:211:10)
at D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongoose\lib\connection.js:709:12
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongoose\lib\connection.js:706:19)
at Mongoose.connect (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongoose\lib\index.js:333:15)
at Object.<anonymous> (D:\Leraning Projects\Mongodb-with-nodeJs\index.js:3:10)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47 {
name: 'MongoParseError',
[Symbol(mongoErrorContextSymbol)]: {}
}
I just tried to run the file using
node "./index.js"
Can I have an solution?
Screen shot 1
Your URL string is not a valid string.
There is a standard structure of URLs i.e.
scheme://host:port/path?query-string#fragment-id
So for making any valid request to some resource, you have to follow the rule. Update your code accordingly.
As the error message already states, you connection string is invalid. I suspect this is because you have two colons after the protocol part (mongodb) in your connection string:
mongodb:://localhost:27017/crudwithnode sould be rather mongodb://localhost:27017/crudwithnode.
Check your connection String.You have two ':' after mongodb whereas it has to be only once.
mongoose.connect('mongodb://localhost/myapp');
You can find better string structuring details at
Mongodb connection String Spec

Resources