Hi, I am Govind Bisen,
I am a fan of MongoDB and I want to learn nodejs to MongoDB atlas connection to connect my front-end react application.
I am facing some issues below is the code that returns values as [object Object] but as a result, i want to have the whole collection. Please help me.
code :
const {MongoClient} = require('mongodb');
async function main(){
const uri = "mongodb+srv://user:password@cluster0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri);
try {
await client.connect();
// We can call whatever function we want to call.
//await listDatabases(client);
// await createListing(client,{
// name:"lovely",
// summary:"A lovely room",
// bedrooms:1
// })
// await createMultipleListings(client,[
// {name:"lovely",
// summary:"A lovely room",
// bedrooms:1},
// {name:"Badly",
// summary:"A BAdly room",
// bedrooms:1}
// ]
// )
findOneListingByName(client);
} catch (error) {
console.log(error);
}
finally{
await client.close();
}
}
main().catch(console.error);
//This will insert multiple document
async function createMultipleListings(client,newListings){
const result = await client.db("sample_airbnb").collection("listingsAndReviews").insertMany(newListings);
console.log(`${result.insertedCount.toString()} new listing with id: ${result.insertedIds}`);
}
// this will only insert one document
async function createListing(client,newListing){
const result = await client.db("sample_airbnb").collection("listingsAndReviews").insertOne(newListing);
console.log(`new listing with id: ${result.insertedId.toString()}`);
}
//show all data or one data findOne, find
async function findOneListingByName(client){
const result = await client.db("sample_airbnb").collection("listingsAndReviews").find({});
if(result){
console.log(`collection : ${result}`); //JSON.stringify(result)// .lean
}
}
// Show all databases
async function listDatabases(client){
const databaselist = await client.db().admin().listDatabases();
console.log("databases - ");
databaselist.databases.forEach(db => {
console.log(` - ${db.name}`);
});
}
output:
C:\Users\govin\OneDrive\Desktop\node-to-mongoCrud> node demo.js
collection : [object Object]