How to use mongoClient in different files - javascript

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");

Related

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();
});
});
}

Show results mongodb nodejs

i need show result in my database mongodb.
Im use mongodb.cloud atlas i already created database now i need show result in my database
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test#cluster0.bvhvj.mongodb.net/*****?
retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("sample_restaurants");
// perform actions on the collection object
// need show result database in console.log
client.close();
});
Im expected result in sample_restaurants.restaurants in console.log
EDIT
Im use your answer but my problème return error
MongoError: no primary server available
this code
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test#cluster0.bvhvj.mongodb.net/****?
retryWrites=true&w=majority";
client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("sample_restaurants").
collection("restaurants").find({}).toArray(function(err,result)
{
if(err) throw err;
console.log(result)
});
});
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test#cluster0.bvhvj.mongodb.net/*****?
retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("sample_restaurants").
collection("restaurants").find({}).toArray(function(err,result)
{
if(err) throw err;
console.log(result)
});
});
First improve your code to fix the error:
let db = await MongoClient.connect(MONGO_URI, { useNewUrlParser: true });
db = await db.db();
const collection = db.collection('sample_restaurants');
You have two different ways to get the data.
1- If your results are not a lot, you can get all of them in once and then print them.
const results = await collection.find({}).toArray();
console.log(results)
2- If the number of the records is something like 2 million records, you can not use it this way. Have to create a cursor and then get them one by one.
const cursor = collection.find();
while(await cursor.hasNext()) {
const record = await cursor.next();
console.log(record);
}

How to modify common mongodb query to async with try and catch

This is my code with written with express js
this query works but I think that using async is more reliable than this
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
const client = new MongoClient(url, { useUnifiedTopology: true });
app.get("/", async (req, res) => {
// this is myquery code with right result
client.connect((err) => {
assert.equal(null, err);
const db = client.db(db_n)
db.collection("list").find({}).toArray((err, result) => {
if(err) throw res.send({ status: "Error when react data", bool: false}).status(450);
res.send(result).status(200);
})
})
});
Try this, not exactly the same as yours, but will give you the idea on how to use async/await with try/catch
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
const client = new MongoClient(url, { useUnifiedTopology: true });
app.get('/', async (req, res) => {
// Connect client if it's not connected
if(!client.isConnected()) {
await client.connect();
// you can also catch connection error
try {
await client.connect();
catch(err) {
return res.status(500).send();
}
}
const db = client.db(db_n);
try {
// Run queries
const result = db.collection("list").find({});
res.json(await result.toArray());
} catch (err) {
// Catch any error
console.log(err.message);
res.status(450).send();
}
});
I have not tested this, but try something along the lines of:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
let client;
const getDb = async () => {
// If we don't have a client, create one.
if (!client) client = new MongoClient(url, { useUnifiedTopology: true });
// If we are not connected, then connect.
if (!client.connected()) await client.connect();
// Get our database
return client.db(db_n);
}
app.get("/", async (req, res) => {
try {
const db = await getDb();
const results = await db.collection("list").find({}).toArray();
res.send(result).status(200);
} catch (err) {
res.send({ status: "Error when react data", bool: false}).status(450);
}
});

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
});

What is wrong with my database file?

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);
});

Categories