Incomplete key value pair for option remote mongodb - node.js

I'm trying to deploy my local node mongoDB app to Heroku. Everything is working fine on my local machine, no errors.
First thing I'm trying to do is to connect to a database on mlab. It seen very straight forward but I get this error:
err { MongoParseError: Incomplete key value pair for option
name: 'MongoParseError',
message: 'Incomplete key value pair for option',
[Symbol(mongoErrorContextSymbol)]: {} }
My code looks like this:
var mongoose = require('mongoose');
const options = {
useNewUrlParser: true
};
mongoose.connect("mongodb://username:password#xxxxx.mlab.com:39251/nameodDB",options).then(
()=>{
console.log("connected to mongoDB")},
(err)=>{
console.log("err",err);
});

MongoDB password needs to be URLEncoded if it consists of special characters like "#" which highlights the start of the host

Related

not able to replace sqllite connection with mysql

I have a small nodejs app that I need to run on MySQL, but as a nodeJS newbie I am having a hard time getting my head around some of the concepts.
Today there is a method (database.js):
async function getLatestHeight() {
return (
await util.promisify(db.get.bind(db))(`SELECT MAX(height) FROM utxos`)
)["MAX(height)"];
}
Which is called like this in app.js:
let height = await db.getLatestHeight();
In database.js I have replaced the connection to sqllite with mysql:
const config = {
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
port: 3306,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DB,
};
dbConnection = mysql.createConnection(config);
dbConnection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
But how do I rewrite the getLatestHeight to send the same query to MySQL? The API seems to work so differently that I am not able to have MySQL return data the same way.
I tried:
return (
await util.promisify(dbConnection.query("SELECT MAX(height) FROM utxos"))
)["MAX(height)"];
But that returns a different type so I get an error TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type function. Received an instance of Query
This is probably a Node newbie issue, so happy for any hjelp. Hard to get my head out of OO and procedural coding styles...

MongooseError: Operation `x.findOne()` buffering timed out after 10000ms

I am using Discord.JS v13 for sharding, and I am using mongoose for the database.
I connect to mongoose in my sharding file (index.js) rather than in the bot.js because I need to use it there, but this isn't allowing me to get data from mongoose anywhere but index.js. I don't know why is this happening as this was perfectly fine a few days back and I haven't changed anything.
index.js (Sharding File)
// .....Sharding Manager
const dbURI = process.env.DBURI;
const mongoose = require("mongoose");
// noinspection JSCheckFunctionSignatures
mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
/models/user.js (Schema File)
const mongoose = require("mongoose");
const userinfo = new mongoose.Schema({
UserID: {
type: String || Number,
required: true,
},
/** Whole schema **/
});
const MessageModel = (module.exports = mongoose.model("muser_userinfo", userinfo));
scommands/filters.js (The File I want to use it at!)
const userinfo = require("../models/user.js");
const user_id = interaction.user.id;
const data = await userinfo.findOne({ UserID: user_id });
if (!data) {
//....
Error
7|muser | MongooseError: Operation muser_userinfos.findOne()` buffering timed out after 10000ms 7|muser | at Timeout.<anonymous> (/root/Bots/muser/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:185:20) 7|muser | at listOnTimeout (node:internal/timers:559:17) 7|muser | at processTimers (node:internal/timers:502:7)
I have tried everything you can possibly think of, used find() instead of findOne(), used .then() on connect, double-checked the credentials and what not!
The ShardingManager generally spawns a process for each shard (unless you specify otherwise). If you're only connecting to your Mongo database from the sharding file then your bot client won't have access to it.
Try connecting to your Mongo database from the client too, it shouldn't matter too much since Mongo supports multiple connections.
In my experience of using mongoose, its throwing an error because of low internet connection, but looking in other documents. this is what ive found that can help you
In my experience this happens when your database is not connected, Try checking out following things -
Is you database connected and you are pointing to the same url from your code.
check if your mongoose.connect(...) code is loading.
I faced this issue where I was running the node index.js from my terminal and mongoose connect code was into different file. After requiring that mongoose code in index.js it was working again. This is the source link --Biggest credit for #Abhishek Gangwar

Failed to connect node.js app to MongoDB Atlas despite using the correct connection credentials

I'm trying to connect my node.js application to MongoDB Atlas but I keep getting a "Bad authentication error" and yes, I am using the current database user credentials.
Here is the snippet that's supposed to connect to MongoDB Atlas
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
console.log('MongoDB Connected: ' +conn.Connection.host)
}catch (err) {
console.error(err)
process.exit(1)
}
}
My terminate shows me bad authentication and some key-pairs that look so:
{
ok: 0,
code: 8000,
codeName: 'AtlasError',
name: 'MongoError'
}
Any ideas why it is not connecting to MongoDB Atlas?
I finally singled out the problem, it was the MongoDB connection string. I was simply inserting my password in the password field without removing the angle brackets.

Mongoose fails to reconnect after replicaset not found error

I'm running a small website that connects to MongoDB Atlas. It has a replicaset with 3 members. For the most part, everything works just fine, but every now an then Atlas' replicaset crashes (or something?) and Mongoose stops working from then on. It throws a single error - MongoError: no primary found in replicaset and that's it.
It doesn't fire mongoose.connection.on('error'), and no errors are reported after this point. It just fails to return any data.
It's sort of hard for me to debug this, as this is running in production, and I have no way of telling when replicaset will fail. Here's how I connect:
function connect() {
tries++;
mongoose.Promise = Promise;
const { uri, options } = config.mongoDb;
return mongoose.connect(uri, options);
}
let db = connect();
db
.connection
.on('error', (err) => {
Raven.captureException(err);
db.disconnect();
})
.on('disconnected', () => {
db = connect();
});
And my options look like this:
options: {
server: {
autoReconnect: true,
ssl: true,
poolSize: 10,
socket_option: {
keepAlive: true
}
}
}
Has anyone had similar problems before? Any idea what I'm doing wrong here, or how to actually catch the error, so I can properly reconnect?

Problems connecting to MongoDB server from MongoLab

I'm trying to connect to mongodb created by MongoLab, but it always seems to fail.
var mongoose = require('mongoose');
mongoose.connect('mongodb://<dbuser>:<dbpassword>#ds123854.mongolab.com:12345/the_db');
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
});
mongoose.connection.on('error', function (err) {
console.log('Could not connect to mongo server!');
console.log(err);
});
// check if mongoose connected; 0 = no; 1 = yes; 2 = connecting; 4 = disconnecting
console.log("mongoose connection: " + mongoose.connection.readyState);
I get the log:
mongoose connection: 2
Could not connect to mongo server!
{ [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }
I tried to check the password, so I did the following in my console:
> mongo ds123854.mongolab.com:12345/the_db -u <dbuser> -p <dbpassword>
MongoDB shell version: 3.0.7
connecting to: ds123854.mongolab.com:12345/the_db
rs-ds123854:PRIMARY> db.mynewcollection.insert({ "foo": "bar"})
WriteResult({ "nInserted" : 1 })
rs-ds123854:PRIMARY> db.mynewcollection.find()
{ "_id" : ObjectId("563c1913504f0ab5cb96d74c"), "foo" : "bar" }
The username and password seem right and I can see that the insert command did put something into the database.
I am hosting my server in localhost, so I believe that's the problem. What sort of things am I missing in my configuration?
Solution: Ensure that your version of Mongoose is up to date.
In my case, I was using version 3.6.13, but the current version is 4.2.4
If you specified your mongoose version, just update your package.json file and use command line npm update

Resources