FruitsProject % node app.js
I run this line on Hyper terminal. And it gives me no response.
Not even an error message did I see.
my app.js code is the following.
const {
MongoClient
} = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'fruitsDB';
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('fruits');
// the following code examples can be pasted here...
collection.insertMany([{
name: "Apple",
score: 8,
review: "Great fruit"
},
{
name: "Orange",
score: 6,
review: "Kinda sour"
}
])
return 'done.';
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
I want to run a mongodb server locally and insert data. How can I do it?
2
Answers
The code at the top of your sample is trying to establish a connection with the Mongo server. You currently cannot add any data using that connection url since there is no Mongo service running locally.
If you’re wanting to run a Mongo server locally, I’d recommend using Docker. In simple terms, Docker is a way of running multiple services on a machine using containers. A container is a running image, which is a stand alone version of a service or application, such as MongoDB. Check out Mongo’s image on Docker Hub at https://hub.docker.com/_/mongo.
Your logging is a bit off, here it is corrected and with request execution time measurement:
If you dont have a local MongoDB instance running, you will likely get the below error after 30s timeout:
You should either install MongoDB locally or use the official Docker image to spin up a local instance, choose according to your needs.