After successfully testing my Node app against a local mongoDB db, I am now trying to connect to our server db - which, unlike my local mongoDB, is user and password protected.
I am running into issues while trying the connection to the server. Specifically, I am getting this error:
MongoError: MongoClient must be connected before calling
MongoClient.prototype.db
The creds I'm trying look something like this:
{
"MONGO_URL": "mongodb://myuser:mypassword#someurl.com:27017?authSource=admin",
"MONGO_DATABASE": "bta",
"MONGO_COLLECTION": "jobs"
}
And here is my connection code:
const config = require('./configuration');
const url = config.get('MONGO_URL');
const dbName = config.get('MONGO_DATABASE');
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(url);
async function getJobDetails() {
client.connect(async function () {
try {
const db = await client.db(dbName);
// do stuff
});
} catch (error) {
console.log(error);
}
});
}
What am I missing here?
I figured out what the issue was and was able to get it to connect. The issue was that the site is secure, so I had to add ssl=true to the url connection string:
const url = 'mongodb://user:password#someurl.com:27017/bta?ssl=true&authSource=admin';
try:
const mongoClient = require('mongodb').MongoClient;
mongoClient.connect(url, { useNewUrlParser: true }, function(client_err, client) {
if (client != null) {
var client_db = client.db(dbName);
}
client.close();
});
As MongoDB.
https://mongodb.github.io/node-mongodb-native/3.2/tutorials/connect/
And please Try double checking DB on the server if it has the right config.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL with password example
const url = 'mongodb://user:password#address:27017?readPreference=primary&authSource=admin';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
This works for both valid localhost/server url
Related
I am trying to connect to MongoAtlas, however I keep getting
Error: invalid schema, expected mongodb
It seems to be that I can connect, but it cannot get my db from MongoAtlas. My try catch error returns me (node:5964) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'collection' of undefined
.env
PORT = 9055
MONGO_URI =mongodb+srv://<my-db-username>:<my-password>#cluster0.vossd.mongodb.net/<db-name>?
retryWrites=true&w=majority
server.js
require('dotenv').config();
const port = Number.parseInt(process.env.PORT, 10);
const mongoUri = process.env.MONGO_URI;
const {MongoClient} = require('mongodb');
const express = require('express');
const Application = require('./application');
const application = Application();
const Health = require('./health');
const Product = require('./product');
const Cart = require('./cart');
const Order = require('./order');
async function main() {
let db;
try {
db = await MongoClient.connect(mongoUri);
console.log(db)
} catch (err) {
console.log(err);
}
application.use('/health', Health());
application.use('/product', Product(db));
application.use('/cart', Cart(db));
application.use('/order', Order(db));
const server = application.listen(port, () => {
const host = server.address().address;
const port = server.address().port;
console.log(`Shopping website server up and running, listening at http://${host}:${port}`);
});
}
main();
Everything works fine when I'm connected to my local db, so I'm unsure as to what I'm doing incorrectly. Any advice is much appreciated. Thank you!
This cannot read property 'collection' of undefined might be misleading as you have caught the error happening on connection. Hence db is null so if you access collection it will give this error. Below is the sample code from Mongo Atlas.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>#test.w7hgn.mongodb.net/<dbname>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true }); // <-- note the option
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
I am reading node.js mongodb driver tutorial
On the sample code below from the tutorial, it closes the client just after it finishes to do whatever it wants to do.
In case of web-server that constantly interacts with mongo, Is it really expected to reconnect to MongoDB and then close the connection with this procedure each time a request is coming? suggestions for better implementations are welcomed :)
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017,localhost:27018/?replicaSet=foo';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected correctly to server");
const db = client.db(dbName);
client.close();
});
You can use this, it uses a connection pool there is no need to close the connection.
var mongoose = require("mongoose");
var db = 'mongodb://localhost/dataBaseName';
mongoose.connect(db, {
useNewUrlParser: true
});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
fs.readdirSync(__dirname + "/models").forEach(function (filename) {
if (~filename.indexOf(".js")) require(__dirname + "/models/" + filename);
});
mongoose.set("useFindAndModify", false);
mongoose.set("useCreateIndex", true);
Not necessary to close and open connection multiple times in same runtime. Connect once when app starts.
I have the following code and I am trying to fetch documents from the MongoDb database and display the first name property of each document. For some reason I get the following error:
TypeError: Cannot read property 'firstName' of undefined
Here is my app.js implementation:
const express = require('express')
const app = express()
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var db = {}
var url = 'mongodb://localhost:27017/bank';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
this.db = db;
console.log("Connected correctly to server.");
db.close();
});
app.get('/customers',function(req,res){
console.log("customers")
this.db.open()
var documents = this.db.collection("customers").find()
documents[0].firstName // how to access the first name property
this.db.close()
res.send("fetching customers")
})
What can i see in code is this.
you have a global scope variable .
var db = {};
and then you are doing
MongoClient.connect(url, function(err, db) {
do staff
when you do
db.close(); the client is close;
})
and when you are opening the this.db.open(); next time the connection is close for mongoclient.
either don't do db.close() or
create mongoclient when you do query
I have tried this:
const mongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:4000,localhost:4001/bookstore?replicaSet=myapp';
mongoClient.connect(url,(err,db)=>{
if(err){
return;
}
console.log('connected to the database');
})
But how to export the database object(db)? The db object can be get only in the callback. Could you please give me some advice?
I am trying to connect to MongoDB with Node.js. MongoClient works fine, but Mongojs doesn't:
var MongoClient = require('mongodb').MongoClient;
var mongojs = require('mongojs');
var url = '...';
MongoClient.connect(url, function(err, client) {
var cursor = client.db("events").collection('events').find();
cursor.each(function(err, event) {
console.log("OK MONGODB");
});
});
mongojs(url, ['events']).events.find(function(err, events) {
events.forEach(function(event) {
console.log("OK MONGOJS");
});
});
"OK MONGODB" is logged several times; "OK MONGOJS" is not.
What's wrong, please?
In your case, the url used in MongoClient should be different with mognojs.
Suppose the url is 'mongodb://localhost/', it is OK for MongoClient. However, the url used in mongojs should be added with dbname as following
var db = mongojs('mongodb://localhost/mydb', ['mycollection']);
So it should be as below
mongojs(url+'events', ['events']).events.find(...);