I tried to set up a mongodb system with my openlayers map, but it is not working : Uncaught TypeError: Cannot read property 'db' of null. My part of code about mongodb is :
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
var tapDB = db.db("tapDB"); //<-- here is the error
})
I suppose that this error is maybe because i am using npm start instear of node server.js, but I am not sure because i am a newbie. Mongodb is started via the cmd by doing the following command :"mongod" and then mongo on an other cmd.
UPDATE: For everyone having the same problem than me, i'd recommand deleting parcel. That's what I did and now it works fine
I believe you are currently providing the url in the wrong place - you need to provide the URL to MongoClient before calling .connect. As per MongoDB's Node.js Driver documentation it should look think this:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'tapDB';
const client = new MongoClient(url);
client.connect(function(err) {
console.log("Connected successfully to server");
const db = client.db(dbName);
// use database connection here
client.close();
});
Have a look a the documentation here: http://mongodb.github.io/node-mongodb-native/3.2/tutorials/connect/
UPDATE:
You can also do the above using ES6 async/await which is in the long run simpler to use than a callback or native promises, this is our setup:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'tapDB';
(async () => { // async/await function that will run immediately
let client;
try {
client = await MongoClient.connect(url);
} catch (err) { throw err; }
console.log("Connected successfully to server");
const db = client.db(dbName);
let res;
try {
res = await db.collection("markers").insertMany([{ test1: true, test2: "3/5" }]);
} catch (err) { throw err; }
try {
await client.close();
} catch (err) { throw err; }
});
Using Javascript Promises ES6 is code is clearer
Look my code
const {MongoClient} = require('mongodb');
MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }).then(client => {
console.log('Connected to MongoDB server')
const db = client.db('dbName')
// Here you can place your operations with the bd
client.close();
}, e => console.log('Error to connect', e))
I hope I've helped
Good luck!
Related
When i try to close the connection between NodeJS and MongoDB cluster i get mongoClient.close is not a function. Please help
Node JS MongoDB code
const mongoClient = require("mongodb").MongoClient;
exports.getInfo = async (czytnik_id) => {
return new Promise((resolve, reject) => {
mongoClient.connect(process.env.URI, { useUnifiedTopology: true }, (err, db) => {
if (err) reject(err);
const dbo = db.db('TTI');
const res = dbo.collection('3P').findOne({ id: czytnik_id });
mongoClient.close()
resolve(res);
});
});
}
According to the docs, the callback in MongoClient.connect() takes an error and a connected client instance, which is the one to be closed. In your case, it seems to be db, so try db.close() instead of mongoClient.close().
From the doc mongodb - npm and Connection guide, MongoClient is a class. You need to create a client instance, the .close method is an instance method.
Example:
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
// the following code examples can be pasted here...
return 'done.';
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
I am creating api using Mongodb and nodeJS as a backend.I have created separate database connection file for that and trying to insert data in other file after importing database file in that.I have connect.js file in db folder and category.js file in routes folder.
But I am getting below error:
TypeError: Cannot read property 'db' of undefined
Below is my code:
connect.js
const MongoClient = require('mongodb').MongoClient;
const dotEnv = require('dotenv').config();
const url = process.env.URI;
const conn = () => {
MongoClient.connect(url,{useNewUrlParser:true,useUnifiedTopology:true})
.then((db) => {
}).catch((err) => {
console.log("error",err);
});
}
module.exports = conn;
category.js
const express = require('express');
const router = express.Router();
const conn = require('../db/connect');
router.get('/',(req,res) => {
data = { name:"Digvijay" };
conn().db("ExpDb").collection("Products").insertOne(data,(err,resp) => {
if(err){
console.log("Error",err);
}
else{
console.log("Success");
}
});
});
module.exports = router;
Someone let me know what I am doing wrong.
I am giving everything in the same file. You can segregate the as per requirement.
const MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
data = { name:"Digvijay" };
db.collection('Products', function (err, collection) {
collection.insert(data);
db.collection('Products').count(function (err, count) {
if (err) throw err;
console.log('Total Rows: ' + count);
});
});
});
it might help to solve the issue.
https://docs.mongodb.com/manual/reference/method/db.collection.insert/#mongodb-method-db.collection.insert
compatible issue with insertOne:
https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/#mongodb-method-db.collection.insertOne
I want to create a db.js file that all my other files can use. The idea is that the connection created in this db.js file can be reused without reconnecting to database everytime i make a call.
db.js
var nodeq = require("node-q");
var connection;
nodeq.connect({host: "192.168.1.1", port: 5000}, function(err, con) {
if (err) throw err;
connection = con;
console.log("KDB connected");
});
module.exports=connection;
I want to do something like above(doesnt work) But the idea is in my app.js i will set
var db = require("./db")
and it will return the connection.
You could wrap the .connect() call in a promise and return this promise from your module, e.g.
const nodeq = require("node-q");
module.exports = new Promise( (resolve,reject) => {
nodeq.connect({host: "192.168.1.1", port: 5000}, function(err, con) {
if (err) return reject(err);
console.log("KDB connected");
resolve(con);
});
});
Then in your caller you can await this promise (still needs error handling, but should give you a start):
const dbConnection = await require("./db");
or you do:
const dbConnPromise = require("./db");
//... then somewhere in your code where you need the db-connection, you can do:
async function doDbStuff() {
const db = dbConnPromise();
const result = await db.query(...);
}
I'm having difficulty using promises with mongo, I simply want to connect and list all the databases, code is as follows:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
// useUnifiedTopology is needed to hide a warning
MongoClient.connect(url, { useUnifiedTopology: true })
.then(db => {
console.log("Connected");
return db.admin().listDataBases()
.then(results => console.log(results))
})
.catch(error => {
console.log(error);
});
I am getting the error db.admin is not a function. What am I doing wrong here?
I had a similar issue recently, I was able to list the databases like this:
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";
const client = new MongoClient(url, {useUnifiedTopology: true});
async function listDatabases() {
const connection = await client.connect();
const adminClient = connection.db().admin();
const dbInfo = await adminClient.listDatabases();
return dbInfo.databases;
}
(async () => {
const databases = await listDatabases();
console.log(databases);
})()
Basically you use the client to connect to the server, then call db() on the connection and get the admin object which allows you to finally read the databases.
I've tried to find a solution to this question in: http://mongodb.github.io/node-mongodb-native/
However, I could not find a solution to listing all available MongoDB databases from a Node.js app.
Use db.admin().listDatabases.
You can do this now with the Node Mongo driver (tested with 3.5)
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost:27017/";
const client = new MongoClient(url, { useUnifiedTopology: true }); // useUnifiedTopology removes a warning
// Connect
client
.connect()
.then(client =>
client
.db()
.admin()
.listDatabases() // Returns a promise that will resolve to the list of databases
)
.then(dbs => {
console.log("Mongo databases", dbs);
})
.finally(() => client.close()); // Closing after getting the data
Only admins can see all the database. So connect to mongodb database with admin creds then create an admin instance by await db.admin(), then list down all databases await adminDB.listDatabases()
const MongoClient = require('mongodb').MongoClient;
let client = await MongoClient.connect(process.env.MONGO_DB_URL);
const db = await client.db(process.env.DEFAULT_DB_NAME);
let adminDB = await db.admin();
console.log(await adminDB.listDatabases());
If you are using mongoose, the below code can be used.
import mongoose from 'mongoose';
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://localhost:27017/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
// Check DB Connection
db.once('open', () => {
(async () => {
const data = await mongoose.connection.db.admin().command({
listDatabases: 1,
});
console.log(data);
})();
console.log('Connected to MongoDB');
});
// Check for DB errors
db.on('error', (err) => {
console.log('DB Connection errors', err);
});
export default mongoose;
If you want to get the database list on your other functions, make sure the connection is established first and also make sure the user has admin access and then just do the below query. This is a sample from my API router.
// Get all databases
router.get('/database/get', async (req, res) => {
try {
const data = await mongoose.connection.db.admin().command({
listDatabases: 1,
});
if (data && data !== null) {
res.status(200).send({ data: data });
return;
}
res.status(200).send({ data: null, message: 'Data not found' });
} catch (e) {
// eslint-disable-next-line no-console
console.log(e);
res.status(500).send(e.message);
}
});
*Its difficult to get list by db.admin().listDatabases, below code will work fine in nodejs *
const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
async function test() {
var res = await exec('mongo --eval "db.adminCommand( { listDatabases: 1 }
)" --quiet')
return { res }
}
test()
.then(resp => {
console.log('All dbs', JSON.parse(resp.res.stdout).databases)
})
test()