its code i have;
const { MongoClient } = require("mongodb");
var db = null // global variable to hold the connection
var url = 'mongodb://0.0.0.0:27017/'
var dbName = 'mydb'
MongoClient.connect(url, (err, client) => {
if (err) {
console.error(err)
} else {
db = client.db(dbName) // once connected, assign the connection to the global variable
console.log(db)// show result
}
})
console.log(db) //result null
how to access 'db' variable in app.js or other module
this script in app.js
var db = require('./mongo.js')
console.log(db); //result empty string
To connect to a MongoDB database in Node.js version 18.13.x using MongoDB version 6.0, you can use the MongoDB driver for Node.js.
First, you need to install the MongoDB driver for Node.js in your project by running the following command:
npm install mongodb
Next, you will need to import the MongoClient class from the MongoDB driver in your Node.js file:
const MongoClient = require('mongodb').MongoClient;
Create a global variable for the database connection:
global.db;
4.Then, you can use the MongoClient.connect() method to connect to your MongoDB database, passing in the connection URL and a callback function to handle any errors or successful connections.
MongoClient.connect('mongodb://<host>:<port>/<dbname>', {useNewUrlParser: true}, (err, client) => {
if(err) throw err;
global.db = client.db(<dbname>);
console.log("Connected to MongoDB");
});
Once the connection is established, you can use the global.db variable to make queries to the database.
global.db.collection('users').find().toArray((err, result) => {
console.log(result);
});
Make sure to replace host, port, and dbname with the appropriate values for your MongoDB setup.
I have been trying W3schools tutorial on nodeJS with MongoDB.
When I try to implement this example in a nodeJS environment and invoke the function with an AJAX call, I got the error below:
TypeError: db.collection is not a function
at c:\Users\user\Desktop\Web Project\WebService.JS:79:14
at args.push (c:\Users\user\node_modules\mongodb\lib\utils.js:431:72)
at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:254:5
at connectCallback (c:\Users\user\node_modules\mongodb\lib\mongo_client.js:933:5)
at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:794:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
Please find below my implemented code:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mytestingdb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("customers").findOne({}, function(err, result) {
if (err) throw err;
console.log(result.name);
db.close();
});
});
Note that the error occurs whenever the execution hits:
db.collection("customers").findOne({}, function(err, result) {}
Also, note (in case it matters) that I have installed the latest MongoDB package for node JS (npm install mongodb), and the MongoDB version is MongoDB Enterprise 3.4.4, with MongoDB Node.js driver v3.0.0-rc0.
For people on version 3.0 of the MongoDB native NodeJS driver:
(This is applicable to people with "mongodb": "^3.0.0-rc0", or a later version in package.json, that want to keep using the latest version.)
In version 2.x of the MongoDB native NodeJS driver you would get the database object as an argument to the connect callback:
MongoClient.connect('mongodb://localhost:27017/mytestingdb', (err, db) => {
// Database returned
});
According to the changelog for 3.0 you now get a client object containing the database object instead:
MongoClient.connect('mongodb://localhost:27017', (err, client) => {
// Client returned
var db = client.db('mytestingdb');
});
The close() method has also been moved to the client. The code in the question can therefore be translated to:
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('mytestingdb');
db.collection('customers').findOne({}, function (findErr, result) {
if (findErr) throw findErr;
console.log(result.name);
client.close();
});
});
I encountered the same thing. In package.json, change mongodb line to "mongodb": "^2.2.33". You will need to uninstall mongodb npm by removing MongoDB Driver/ node_modules or etc , then install npm to install this version.
This resolved the issue for me. Seems to be a bug or docs need to be updated.
For those that want to continue using version ^3.0.1 be aware of the changes to how you use the MongoClient.connect() method. The callback doesn't return db instead it returns client, against which there is a function called db(dbname) that you must invoke to get the db instance you are looking for.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
MongoClient.connect(url (err, client) => {
if(err) throw err;
let database = client.db('databaseName');
database.collection('name').find()
.toArray((err, results) => {
if(err) throw err;
results.forEach((value)=>{
console.log(value.name);
});
})
})
The only problem with your code is that you are accessing the object that's holding the database handler. You must access the database directly (see database variable above). This code will return your database in an array and then it loops through it and logs the name for everyone in the database.
Piggy backing on #MikkaS answer for Mongo Client v3.x, I just needed the async / await format, which looks slightly modified as this:
const myFunc = async () => {
// Prepping here...
// Connect
let client = await MongoClient.connect('mongodb://localhost');
let db = await client.db();
// Run the query
let cursor = await db.collection('customers').find({});
// Do whatever you want on the result.
}
I did a little experimenting to see if I could keep the database name as part of the url. I prefer the promise syntax but it should still work for the callback syntax. Notice below that client.db() is called without passing any parameters.
MongoClient.connect(
'mongodb://localhost:27017/mytestingdb',
{ useNewUrlParser: true}
)
.then(client => {
// The database name is part of the url. client.db() seems
// to know that and works even without a parameter that
// relays the db name.
let db = client.db();
console.log('the current database is: ' + db.s.databaseName);
// client.close() if you want to
})
.catch(err => console.log(err));
My package.json lists monbodb ^3.2.5.
The 'useNewUrlParser' option is not required if you're willing to deal with a deprecation warning. But it is wise to use at this point until version 4 comes out where presumably the new driver will be the default and you won't need the option anymore.
It used to work with the older versions of MongoDb client ~ 2.2.33
Option 1: So you can either use the older version
npm uninstall mongodb --save
npm install mongodb#2.2.33 --save
Option 2: Keep using the newer version (3.0 and above) and modify the code a little bit.
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client){
if(err) throw err;
let db = client.db('myTestingDb');
db.collection('customers').find().toArray(function(err, result){
if(err) throw err;
console.log(result);
client.close();
});
});
I solved it easily via running these codes:
npm uninstall mongodb --save
npm install mongodb#2.2.33 --save
Happy Coding!
If someone is still trying how to resolve this error, I have done this like below.
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'mytestingdb';
const retrieveCustomers = (db, callback)=>{
// Get the customers collection
const collection = db.collection('customers');
// Find some customers
collection.find({}).toArray((err, customers) =>{
if(err) throw err;
console.log("Found the following records");
console.log(customers)
callback(customers);
});
}
const retrieveCustomer = (db, callback)=>{
// Get the customers collection
const collection = db.collection('customers');
// Find some customers
collection.find({'name': 'mahendra'}).toArray((err, customers) =>{
if(err) throw err;
console.log("Found the following records");
console.log(customers)
callback(customers);
});
}
const insertCustomers = (db, callback)=> {
// Get the customers collection
const collection = db.collection('customers');
const dataArray = [{name : 'mahendra'}, {name :'divit'}, {name : 'aryan'} ];
// Insert some customers
collection.insertMany(dataArray, (err, result)=> {
if(err) throw err;
console.log("Inserted 3 customers into the collection");
callback(result);
});
}
// Use connect method to connect to the server
MongoClient.connect(url,{ useUnifiedTopology: true }, (err, client) => {
console.log("Connected successfully to server");
const db = client.db(dbName);
insertCustomers(db, ()=> {
retrieveCustomers(db, ()=> {
retrieveCustomer(db, ()=> {
client.close();
});
});
});
});
I have MongoDB shell version v3.6.4, below code use mongoclient, It's good for me:
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var url = 'mongodb://localhost:27017/video';
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, client)
{
assert.equal(null, err);
console.log("Successfully connected to server");
var db = client.db('video');
// Find some documents in our collection
db.collection('movies').find({}).toArray(function(err, docs) {
// Print the documents returned
docs.forEach(function(doc) {
console.log(doc.title);
});
// Close the DB
client.close();
});
// Declare success
console.log("Called find()");
});
MongoDB queries return a cursor to an array stored in memory. To access that array's result you must call .toArray() at the end of the query.
db.collection("customers").find({}).toArray()
Late answer but maybe someone will need it in future
we can create async function which one will return our collection and db instances
const dBInstances = async () => {
const collection = await db
.then((client) => {
const db = client.db();
const collection = db.collection("AGGREGATION");
return { collection: collection, db: db };
})
.catch((err) => {
console.log(`Data base instances error ${err}`);
});
return collection;
};
and after we can use result of execution dBInstances() by this way i used JS destructurisation in example below
const test = async (req, res) => {
const { collection, db } = await dBInstances();
console.log(collection);
console.log(db);
};
now we have separated access to our db and collection.
Recently I had the same issue, I finally resolved it using MongoDB official website documentation and sample codes.
My MongoDB client version is "mongodb": "^4.4.1" and I managed to insert a document finally without needing to downgrade my MongoDB package according to the approved answer which seems to be obsolete.
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.
const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db("insertDB");
const haiku = database.collection("haiku");
// create a document to insert
const doc = {
title: "Record of a Shriveled Datum",
content: "No bytes, no problem. Just insert a document, in MongoDB",
}
const result = await haiku.insertOne(doc);
console.log(`A document was inserted with the _id: ${result.insertedId}`);
} finally {
await client.close();
}
}
run().catch(console.dir);
I have the following code written a file called app.js. MongoDB is installed on 192.168.16.1, which is my laptop. When I run this using node app.js command, I get a message "connected".
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongoose = require('mongoose');
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://192.168.16.1:27017/angularcrud", function (err, db) {
if(err) {console.log(err); }
else {console.log('connected');}
});
\
I have an OpenWhisk environment setup on my laptop using Vagrant. If is ssh to vagrant and ping to 192.168.16.1, I get ping response, so I am sure that vagrant VM is able to reach 192.168.16.1. I have written the following code in NodeJS to create an OpenWhisk action. I have deployed it into openwhisk as a .zip file (which includes Node_modules folders also).
function entryPoint(args) {
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var message = "Connection not SET";
var mongoose = require('mongoose');
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://193.168.16.1:27017/angularcrud", function (err, db) {
if(err) {return err;}
else {return 'success';}
});
}
module.exports.main = entryPoint;
If I run the above code in OpenWhisk, I get a result {}. If I remove the MongoClient.Connect statement and return a simple string, then I am getting the string when I invoke the action. I am sure there is something wrong in the MongoClient.Connect, when run on OpenWhisk. But, I am really stuck, because I get no error to tell me what is going wrong.
The entryPoint function executes an asynchronous function to connect to the database. When executing asynchronous function calls, you need to return a Promise from the action handler. This ensures the platform will block on that asynchronous result before completing the invocation.
function main() {
return new Promise((resolve, reject) => {
MongoClient.connect(URL, (err, db) => {
if(err) return reject(err)
resolve({message: "success"})
})
})
}
There appears to be a lot of documentation (e.g. https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js, but also elsewhere including this site) indicating that the proper method of connecting with the pg.js Node package is using pg.connect. However, I attempted (after previous problems with my actual code) to test by using the exact code shown on the aforementioned Heroku documentation:
var pg = require('pg');
pg.defaults.ssl = true;
pg.connect(process.env.DATABASE_URL, function(err, client) {
if (err) throw err;
console.log('Connected to postgres! Getting schemas...');
client
.query('SELECT table_schema,table_name FROM information_schema.tables;')
.on('row', function(row) {
console.log(JSON.stringify(row));
});
});
And I got the error message "pg.connect is not a function". What is going on, and how do I fix it?
A new version of pg, namely 7.0.0, was published about 15 hours ago (from the time I'm writing this).
This version has lots of changes, one of them being that pg.connect has been hard-deprecated (in other words: removed) in favor of pg.Pool(...).connect(...), as documented here: https://node-postgres.com/guides/upgrading
The new method of connecting looks like this:
var pool = new pg.Pool()
// connection using created pool
pool.connect(function(err, client, done) {
client.query(/* etc, etc */)
done()
})
// pool shutdown
pool.end()
Lots of older documentation will not reflect these changes, so the example code they use won't work anymore.
You can either try and rewrite the example code so it works in 7.0.0, or explicitly install an older version that will still work with the example code:
npm install pg#6
pg: postgresql => (https://www.npmjs.com/package/pg)
⚠️ pg.connect is deprecated since version 6.3 ❌
BE CAREFUL : Instead there is another method called pool
Here is how you can set up node-postgres easily with express.
const pg = require('pg');
const express = require('express');
const app = express();
const config = {
user: 'postgres',
database: 'YOURDBNAME',
password: 'YOURPASSWORD',
port: 5432 //Default port, change it if needed
};
// pool takes the object above -config- as parameter
const pool = new pg.Pool(config);
app.get('/', (req, res, next) => {
pool.connect(function (err, client, done) {
if (err) {
console.log("Can not connect to the DB" + err);
}
client.query('SELECT * FROM GetAllStudent()', function (err, result) {
done();
if (err) {
console.log(err);
res.status(400).send(err);
}
res.status(200).send(result.rows);
})
})
});
app.listen(4000, function () {
console.log('Server is running on port 4000');
});
If you want to stick with the code you have you can use an older version of Postgres.
First, apply:
npm uninstall postgresql
and then install version 6.1.2 (which is compatible with the code you mentioned):
npm install pg#6.1.2
var express = require('express');
var app = express();
const pgp = require('pg-promise')();
var connectionString = "";
var parse = require('pg-connection-string').parse;
try {
var connectionString = "postgres://USERNAME:#localhost:5432/DBNAME";
var config = parse(connectionString);
config.password = "PASSWORD";
var dbcon = pgp(config);
app.set('dbCon', dbcon);
}
catch (error) {
console.log("DB error")
}
module.exports = app;
I've encountered a bizarre error trying to connect to a MongoHQ MongoDB on Heroku using NodeJS. It worked before and now it has stopped to work. I can connect to database on my local machine, so I guess that MongoHQ is working just fine. On Heroku, the following minimal example throws "Error: failed to connect to [mongodb://xyz.mongohq.com]". Any idea what's wrong?
var Fiber = require('fibers');
var MongoSync = require("mongo-sync");
Fiber(function() {
try {
var server = new MongoSync.Server("mongodb://xyz.mongohq.com:12345");
var db = server.db("app12345678");
db.auth("heroku", "password");
var collection = db.getCollection("my_collection");
console.log(collection.count());
} catch (e) {
console.log(e);
}
process.exit(0);
}).run();
Try specifying the database name and auth credentials all in the connection string.
mongodb://heroku:password#xyz.mongohq.com:12345/app12345678
You could also try connecting using MongoClient and connect as outlined in the driver readme doc.
var MongoClient = require('mongodb').MongoClient,
format = require('util').format;
MongoClient.connect(' mongodb://heroku:password#xyz.mongohq.com:12345/app12345678', function(err, db) {
if(err) throw err;
var collection = db.collection('my_collection');
collection.insert({a:2}, function(err, docs) {
collection.count(function(err, count) {
console.log(format("count = %s", count));
});
});
});
If that still doesn't work double check everything--recreate the user you want to connect with and then copy the connection string from MongoHQ's admin page replacing the username and password you just created.