mongodb connection db is undefined with mongoose - mongodb

I am connecting using Mongoose using the following way
import { createConnection } from 'mongoose';
this.m_context = createConnection('mongodb://localhost/master')
But when I try to access this.m_context.db it is giving me undefined.
What am I doing wrong here? I checked the connection string that is working fine in the compass.

What I found is, createConnection doesn't open connection and because of that, it was giving undefined, as it gives connection DB info only if the connection is open.
this.m_context = await new Promise<Connection>((resolve) => {
createConnection('mongodb://localhost/master', undefined, (error, result) => {
resolve(result)
});
});

Related

MongoDB error when trying to connect to it

trying to get my code to connect to mongodb.
I have start mongo db compass, rund mongosh and mongod in cmd
add a new db to mongodb.
edit a new url to connect.
run npm start and get this and i dont connect to mongodb:
(node:14420) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version.
To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use `node --trace-warnings ...` to show where the warning was created)
my db.ts
import { MongoClient } from 'mongodb';
// Connection URL
const url = 'mongodb://127.0.0.1:27017';
// Database Name
const dbName = 'xxxxx';
// Create a new MongoClient
export async function initMongo() {
try {
const client = new MongoClient(url,{ useNewUrlParser: true });
await client.connect();
const db = client.db(dbName);
at the bottom of db
} catch (e) {
console.log('Cannot connect to MongoDB. Will retry in 10 seconds ...');
await new Promise<void>(resolve => {
setTimeout(() => resolve(), 10000);
});
console.log('Retrying...');
return await initMongo();
}
await client.connect
connect have a line right true.

Getting MongoParseError: Invalid message size: 1347703880, max allowed: 67108864

I am building a RESTful BLogAPP where my stack is MEN
while connecting to mongo server i am getting this error
These were working But this happened
My Mongo file code
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const url = "mongodb://localhost/127.0.0.1:27017/Blog";
mongoose.connect(url ,{
useNewUrlParser: true,
useUnifiedTopology: true
})
const db = mongoose.connection;
db.once("open", (_) => {
console.log("Database connected:", url);
});
db.on("error", (err) => {
console.error("connection error:", err);
});
module.exports = mongoose;
My app.js
const mongoose = require("./server/mongoose");
It was resolved for me after remove server port from connection string. Replace mongodb connection string From
const url = "mongodb://localhost:27017/Blog";
To
const url = "mongodb://localhost/Blog";
I got the same error message and I've finally solved it. Try to leave it like this:
const url = "mongodb://localhost:27017/Blog";
I too got the same error while accessing MongoDB via mongoose.
The URI I set was MONGO_URI=mongodb://localhost:3000/myDB.
The port was wrong.
I solved it by correcting the Mongo URI.
MONGO_URI=mongodb://localhost:27017/myDB.

Mongodb Atlas Express.js Error: getaddrinfo ENOTFOUND

I want to connect my express app to my mongoDb Atlas cluster.I'm from Iran, and cloud databases are sanctioned for us. I used VPN to bypass it in order to be able to practice.
Is there some coding mistake that I've done or is it because of using VPN?
The error:
(node:9008) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
connected
events.js:174
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND
is listening...
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
Emitted 'error' event at:
at GetAddrInfoReqWrap.doListen [as callback] (net.js:1448:12)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:17)
[nodemon] app crashed - waiting for file changes before starting...
And the code:
database.js
----------------
const mongoDb = require('mongodb');
const MongoClient = mongoDb.MongoClient;
let _db;
const mongoConnect = callback => {
MongoClient.connect(
'mongodb+srv://<someUser>:<somePassword>#<someCluster>-zh1eb.mongodb.net/test?retryWrites=true'
)
.then(client => {
console.log('\nconnected\n');
_db = client.db();
callback();
})
.catch(err => {
console.log('\nerror\n', err);
throw err;
});
};
const getDb = () => {
if (_db) {
return _db;
}
throw 'NO DATABASE FOUND';
};
exports.mongoConnect = mongoConnect;
exports.getDb = getDb;
app.js
------------
...
const mongoConnect = require('./util/database').mongoConnect;
...
mongoConnect(() => {
app.listen(3000, '\nis listening...\n');
});
I found out what was the problem:
mongoConnect(() => {
app.listen(3000, '\nis listening...\n');
});
should actually be
mongoConnect(() => {
app.listen(3000, () => { console.log('\nis listening...\n');});
});
Silly me... :)
For those having such issue:
first check out whether the source of problem is your code or the connection to MongoDb.
That is instead of choosing "connect your application" select "connect with Mongodb Compass".
If the Mongodb Compass could connect and show your cluster, then definitely there is something wrong with your code, esp. how it's coded to connect.

Mongo connection occasionally makes the lambda function timeout

I have been using MLab MongoDB and mongoose library to create a db connection inside a serverless (Lambda) handler. It works smoothly on local machine. But sometimes it doesn't work after deployment.The request returns an Internal server error. The weird thing is sometimes it works. But If I remove the database connection code, the handler works. The serverless log just says Process exited before completing request. No real errors so no idea what to do.
The db connection looks like this:
handler.js
// Connect to database
mongoose.connect(process.env.DATABASE_URL, {
useMongoClient: false
}).then((ee) => {
console.log('------------------------invoke db ', ee);
})
.catch(err => console.error('-----------error db ', err));
No error in here too. Any idea what's happening?
When you get Process exited before completing request, it means that the node process has crashed before Lambda was able to call callback. If you go to Cloudwatch logs, there would be an error and stack trace of what happened.
You should connect to the MongoDB instance inside your handler and before you call callback(), disconnect first.
It would be like this...
exports.handler = (event, context, callback) => {
let response;
return mongoose.connect(process.env.DATABASE_URL, {
useMongoClient: false
}).then((ee) => {
// prepare your response
response = { hello: 'world' }
}).then(() => {
mongoose.disconnect()
}).then(() => {
// Success
callback(null, response)
}).catch((err) => {
console.error(err);
callback(err);
})
};
Here is an article explaining with details how lambda work with node and an example of how to implement DB connection.
Differently of #dashmug suggested, you should NOT disconnect your DB since connecting every time will decrease your performance.

Node.js connect-mongo database connection problem

This is a very weird problem with "connect-mongo"
In my server, I have two scripts.
1) create the express server with session with Mongo DataStore: It has no problem for connection or creating the session.
MongoStore = require('connect-mongo'),
app = require('express').createServer(
express.session({ secret: cfg.wiki_session_secret,
store:new MongoStore({
db: 'mydatabase',
host: '10.10.10.10',
port: 27017
})
})
);
2) just create the store without express:
var MongoStore = require('connect-mongo');
var options = {db: 'mydatabase'};
var store = new MongoStore(options, function() {
var db = new mongo.Db(options.db, new mongo.Server('10.10.10.10', 27017, {}));
db.open(function(err) {
db.collection('sessions', function(err, collection) {
callback(store, db, collection);
});
});
});
That will throw the connection problem:
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Error connecting to database
at /home/eauser/node_modules/connect-mongo/lib/connect-mongo.js:106:13
at /home/eauser/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:79:30
at [object Object].<anonymous> (/home/eauser/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connections/server.js:113:12)
at [object Object].emit (events.js:64:17)
at Array.<anonymous> (/home/eauser/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection.js:166:14)
at EventEmitter._tickCallback (node.js:126:26)
I just don't know why..
connect-mongo is a middleware for the connect framework, which express is based on.
So, you must use the middleware with the express framework or the connect framework, otherwise it won't work. It's not written to be a standalone session library.
You can go for mongoose to connect. Install using npm command
npm install mongoose
Install mongoose globally
npm install -g mongoose
app.js
var mongoose = require("mongoose");
This module has callback in the constructor which is called when the database is connected, and the collection is initialized so it won't work as you expect.
I've the same problem than you and I wanted the same interface that you aim here. So I wrote another module called YAMS - Yet Another Mongo Store. This is an example with YAMS:
var MongoClient = require("mongodb").MongoClient;
var Yams = require('yams');
var store = new Yams(function (done) {
//this will be called once, you must return the collection sessions.
MongoClient.connect('mongo://localhost/myapp', function (err, db) {
if (err) return done(err);
var sessionsCollection = db.collection('sessions')
//use TTL in mongodb, the document will be automatically expired when the session ends.
sessionsCollection.ensureIndex({expires:1}, {expireAfterSeconds: 0}, function(){});
done(null, sessionsCollection);
});
});
app.usage(express.session({
secret: 'black whisky boycott tango 2013',
store: store
}));
This is in my opinion more flexible than the connect-mongo middleware.