Show results mongodb nodejs - javascript

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

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 read properties of undefined (reading ‘db’)

My mongodb info etc. I entered it correctly, but every time I try to run the code, I keep getting this error. Attached is some of my code and a picture of the error.
error
Source Code
const vars = require("../variables");
const url = vars.dbLink; // vars.dbLink
const dbName = "channels";
var database;
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
function connect(callback) {
MongoClient.connect(url, { useNewUrlParser: true }, (err, res) => {
const db = res.db(dbName);
database = db;
return callback(err);
});
}

Getting error while connecting to mongo in aws lambda

I am trying to connect to mongo database using mongodb but its throwing error unable to resolve.
This is my mongo connect fucntion
const {
MongoClient,
ObjectId,
} = require('mongodb');
const {
MERCURY_MONGO_DB_URL,
} = process.env;
const initialize_mongodb_database_connection = async () => {
//
// Create a new MongoClient
//
const connection = new MongoClient(MERCURY_MONGO_DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Use connect method to connect to the Server
connection.connect((err) => {
if (err != null) {
console.log(`MongoDB Connection :: Error :: ${err}`);
process.exit(1);
} else {
const db = connection.db('demo');
return db;
global.ObjectId = ObjectId;
console.log('MongoDB Connection :: Ready');
}
});
};
module.exports = {
initialize_mongodb_database_connection,
};
And this is where I am trying to use it but getting error
var db = await initialize_mongodb_database_connection();
const data = await db.collection(`access_log_${result.student_uuid}`)
.find(where)
.toArray();
console.log(data)
I am getting error of this Cannot read property 'collection' of undefined
where actually I have data at collection access_log_1747386c-9577-4073-b818-649db0ce9d50
not sure why it isn't working? I have that collection in my db.
Can any one help here? Also I am developing this for aws lamdba
The error message is saying the db object is undefined. When looking at your initialize_mongodb_database_connection function, you're not returning the promise returned by MongoClient#connect.
const initialize_mongodb_database_connection = async () => {
...
return connection.connect((err) => {
...
});
};

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

Categories