What is wrong with my database file? - javascript

this is my database.js file:
const MongoClient = require('mongodb').MongoClient;
const db = function(){
return MongoClient.connect('mongodb://localhost:27017/users', (err, database) => {
if (err) return console.log(err);
return database;
});
}
module.exports = db;
I icluded it to my server.js like this:
var db = require('./database');
but when I want to use it like this
db().collection('orders')
I am getting a TypeError (Cannot read property 'collection' of undefined)
Edit: sorry, I made an issue during writing this question of course I used db().collection

The issue is with your export, and misunderstood behavior of node's callbacks.
const MongoClient = require('mongodb').MongoClient;
const db = function(){
return MongoClient.connect('mongodb://localhost:27017/users', (err, database) => {
// this is inside a callback, you cannot use the database object outside this scope
if (err) return console.log(err);
return database; // this database object is what you should be exporting
});
}
module.exports = db; // You are exporting the wrong variable
One way to fix this is (may not be the best) to export the database object that we receive in the callback. Example:
const MongoClient = require('mongodb').MongoClient;
let database = null;
MongoClient.connect('mongodb://localhost:27017/users', (err, db) => {
if (err) return console.log(err);
database = db;
});
module.exports = database;
And now you can use the db, but with a null check.
var db = require('./database');
if (db !== null) {
db.collection('orders').find({}, (err, docs) => {
if (err) return console.log(err);
console.log(docs);
});
}
But this may lead to connection being established again and again when you require the database.js file (I am not sure about this). A better approach would be:
const MongoClient = require('mongodb').MongoClient;
let database = null;
const connect = () => {
if (database !== null) return Promise.resolve(database);
return new Promise((resolve, reject) => {
MongoClient.connect('mongodb://localhost:27017/users', (err, db) => {
if (err) return reject(err);
database = db;
resolve(database);
});
});
};
module.exports = connect;
and then use it like:
var dbConnect = require('./database');
dbConnect().then((db) => {
db.collection('orders').find({}, (err, docs) => {
if (err) return console.log(err);
console.log(docs);
});
}).catch((err) => {
console.error(err);
});

Related

How to use mongoClient in different files

In the application, in different files, I need to perform different functions with MongoDB. In one file I record users. And in the second one, you need to output all the documents in the collection to the console. How can I use mongoClient in another file. That connection was only in one file. I tried using module.exports but got an error - mongoClient.connect is not a function. How can i do this?
add_users.js:
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost:27017/";
const mongoClient = new MongoClient(url);
module.exports = {
mongoClient
};
let users = [{
name: "Bob",
},
{
name: "Alice",
},
];
mongoClient.connect(function(err, client) {
const db = client.db("expensesdb");
const collection = db.collection("users");
collection.insertMany(users, function(err, results) {
if (err) {
return console.log(err);
}
console.log(results);
client.close();
});
});
find_doc.js:
const mongoClient = require("./add_users");
mongoClient.connect(function (err, client) {
const db = client.db("expensesdb");
const collection = db.collection("users");
if (err) return console.log(err);
collection.find().toArray(function (err, results) {
console.log(results);
client.close();
});
});
You should change your import statement to:
const { mongoClient } = require("./add_users");

Cannot retrieve all entries from MongoDB collection

i'm trying to retrieve all entires from mongo yet I keep on getting an error that I couldn't find any while having there are some entries.
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'toy_db';
tryMongo();
function tryMongo() {
MongoClient.connect(url, (err, client) => {
if (err) return console.log('Cannot connect to DB');
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('toy');
collection.find().toArray((err, docs) => {
if (err) return console.log('cannot find toys');
console.log('found these:');
console.log(docs);
});
client.close();
});
}
this is the error i'm getting :
Server listening on port 3030!
Connected successfully to server
cannot find toys
I have also added a picture of mongo
appreciating any kind of help!
You are closing mongo connection before you get response from server. Move client.close(); inside toArray callback.
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'toy_db';
tryMongo();
function tryMongo() {
MongoClient.connect(url, (err, client) => {
if (err) return console.log(err);
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('toy');
collection.find().toArray((err, docs) => {
if (err) {
console.log(err);
} else {
console.log('found these:');
console.log(docs);
}
client.close();
});
});
}

Node JS MongoDB collection.find.toArray returns no value

I'm building a website that lets people write sticky notes and print it to them on the screen. I want to store the sticky notes inside a mongoDB with a db called stickyNotes and a collection called stickyNotes which currently has two documents.
I have a variable called stickyNotes which suppose to get the documents from the stickyNotes collection on the db but when I use the collection.find.toArray from the mongodb library to enter the documents to the stickyNotes variable in an asynchronous way, it shows an empty array value.
This is my server.js file:
const express = require("express");
const mongo = require("mongodb").MongoClient;
const app = express();
let stickyNotes = [];
//mongodb get all sticky notes
const mongoUrl = "mongodb://localhost:27017";
mongo.connect(mongoUrl, { useNewUrlParser: true }, async function(
err,
connection
) {
if (err) {
console.error(err);
} else {
console.log("Succesfully connected to the database");
const db = connection.db("stickyNotes");
const stickyNotesCollection = db.collection("stickyNotes");
stickyNotes = await stickyNotesCollection.find({}).toArray();
}
connection.close();
});
console.log(stickyNotes);
app.use(express.static("./src/public"));
app.get("/sticky-notes", (req, res) => {
console.log("Got a request for sticky notes");
res.json(stickyNotes);
});
const port = 3000;
app.listen(port, () => {
console.log(`App is running on port ${port}`);
});
Can try with:
stickyNotesCollection.find({}, (err, result) => {
if (err) throw err;
stickyNotes = result;
});
or find result in array:
collection.find().toArray(function(err, result) {
console.log(result);
});
or iterate:
collection.find().each(function(err, result) {
//once result
});

Every second run throws: MongoError: Topology was destroyed

I am building a REST API but every second time I load my site I get a MongoError: Topology was destroyed. Can someone help me fixing this? I have a feeling that there is something wrong with the asynchronous running.
const client = new MongoClient(apiconfig.mongoUrl, {
useNewUrlParser: true
});
app.get("/api/:object", (req, res) => {
mongodb(req.params["object"], async (collection: Collection) => {
if (collection !== undefined) {
let result = await collection.find().toArray();
res.send(result);
}
else {
res.sendStatus(404);
}
});
});
const mongodb = (coll: string, operation: (collection: Collection) => Promise<void>) => {
client.connect((err) => {
const db = client.db("VaorraJS");
db.collections().then((collections) => {
operation(collections.find((collection) => collection.collectionName === coll)).then(() => {
client.close();
});
}).catch((error) => {
console.log("ERROR: " + error);
});
});
}
app.listen(5000);
I would suggest the use Mongoose
you are creating DB connection for every request, which is not the correct way
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = '<some db>';
// Use connect method to connect to the server
let db;
MongoClient.connect(url, function (err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
db = client.db(dbName);
});
app.get("/api/:object", async(req, res) => {
const collection = db.collection(req.params["object"]);
let result = await collection.find().toArray();
res.send(result);
});

How to call mongodb collection getall by node.js?

I wanna take the whole list of notifies from mongo db but it returns empty([]) array also I know that i need callback or shorter way of it . Do you have any idea for collecting any data from mongodb by node.js? If I call this /Notifies method (http://127.0.0.1:5000/Notifies)
var MongoClient = require('mongodb').MongoClient;
var express = require("express");
var app = express();
format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
});
return res.json(arr);
});
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function () {
console.log("Listening on " + port);
})
Don't use for docs.each instead of this use .toArray so it will return directly a array and then use Json.stringify to convert it into json string array
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
coll.find({}).toArray(function (err, result) {
if (err) {
res.send(err);
} else {
res.send(JSON.stringify(result));
}
})
});
The problem is you are returning the empty array from within the function, before the actual DB operation occurs. You need to move the line return res.json(arr);
into the find function:
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
console.log(docs);
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
return res.json(arr);
});
});
});
Also, for future use, do not reuse variable names in nested functions (you have 3 functions that use the variable err).

Categories