Mongodb Connect error: Just cant connect to the database - node.js

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

Related

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

No AuthProvider for DEFAULT defined with mongoose 6

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

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?

Unable to create a DB using mongoose even with mongod running

I have mongod running in one tab, mongo shell works perfectly in another.
Here is my code, I have mongoose version 5.9.10 installed in my project folder using npm and mongodb 3.5.6
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27071/fruitsDB", { useUnifiedTopology: true,useNewUrlParser: true, useFindAndModify:false, useCreateIndex:true });
const fruitSchema = new mongoose.Schema ({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit ({
name: "Apple",
rating: 8,
review: "gud"
});
fruit.save();
run, get a bunch of errors and warnings and no db is created according to mongo shell
Here is what the error I'm getting when I do node app.js in hyper
UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27071
at new MongooseServerSelectionError (C:\Users\ahuja\Desktop\code\Web Development\fruitsProj\node_modules\mongoose\lib\error\serverSelection.js:22:11)
at NativeConnection.Connection.openUri (C:\Users\ahuja\Desktop\code\Web Development\fruitsProj\node_modules\mongoose\lib\connection.js:823:32)
at Mongoose.connect (C:\Users\ahuja\Desktop\code\Web Development\fruitsProj\node_modules\mongoose\lib\index.js:333:15)
at Object.<anonymous> (C:\Users\ahuja\Desktop\code\Web Development\fruitsProj\app.js:3:10)
at Module._compile (internal/modules/cjs/loader.js:1156:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
(node:7980) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
mongoose
.connect("mongodb://localhost/fruitsDB", { useUnifiedTopology: true,useNewUrlParser: true, useFindAndModify:false, useCreateIndex:true })
.then(() => {
log.info("successfully connected to db");
})
.catch((err) => {
log.error("db connection failed " + err);
});

Azure Chatbot fails with "SyntaxError: Unexpected identifier - cosmosClient.databases.createIfNotExists" while connecting to CosmosDB

I am extremely new to Azure Bot Services and the Azure platform as a whole.
I am trying to create a Chatbot using node.js but I am getting the below error while trying to connect to CosmosDB.
The bot was running fine before I added the below code to connect to CosmosDB.
Any help or guidance on this would be appreciated!
P.S. - I have added the '#azure/cosmos' package and the code runs without any error if I just remove the try-catch segment.
Code for connecting to CosmosDB:
var async=require("async");
var await=require("await");
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
async function readDatabase() {
const { body: databaseDefinition } = await cosmosClient.database(databaseId).read();
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}
Error Message:
Sat Jan 12 2019 03:40:08 GMT+0000 (Coordinated Universal Time): Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
You can't await without being in an async function.
Dump all your code into a async function main(){} method, then call main().catch((err) => console.log(err)); or some similar thing to start the promise and handle errors.
You can see a sample of that kind of pattern here in this sample: https://github.com/Azure/azure-cosmos-js/blob/master/samples/ChangeFeed/app.js#L33
--- EDIT 1 ---
Here's your sample rewritten with Promises:
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
cosmosClient.database(databaseId).read().then(({body: databaseDefinition}) => {
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}).catch((err) {
console.err("Something went wrong" + err);
});
For your sample above, you don't need to import async/await, they are keywords in JavaScript now.
Here's a blog post that compares and contrasts Async/Await and Promises: https://hackernoon.com/should-i-use-promises-or-async-await-126ab5c98789

Resources