I installed MongoDB Community Server and also installed the MongoSH shell package on my computer.
I then created a new database & collection using MongoSH which worked fine even with CRUD operations.
I then created a new project folder to run an app.js using Node (I installed mongodb@4.13 driver as per instructions on the documentations) but after running the following:
const { MongoClient } = require("mongodb");
const url = "mongodb://localhost:27017";
const client = new MongoClient(url);
async function run() {
try {
const database = client.db("fruitsDB");
const fruits = database.collection('fruits');
// create an array of documents to insert
const docs = [
{ name: "Pineapple", score: 1, review: "Great fruit"},
{ name: "Guava", score: 5, review: "Kinda sour"},
{ name: "Rambutan", score: 10, review: "Great stuff!"}
];
// this option prevents additioanl documents from being inserted if one fails
const options = { ordered: true};
const result = await fruits.insertMany(docs, options);
console.log(`${result.insertedCount} documents were inserted`);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
I went over to my MongoSH shell and ran show dbs
However, this new fruitsDB did not show up in the list of databases.
I thought I had somehow failed the CRUD operations in the app.js file and thus modified my app.js file to query for the data I had inserted above:
const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const url = "mongodb://localhost:27017";
const client = new MongoClient(url);
async function run() {
try {
const database = client.db("fruitsDB");
const fruits = database.collection('fruits');
// Query for fruit with name 'Orange'
const query = { name: "Rambutan"};
const options = {
projection: { _id: 0, score: 1}
}
const fruit = await fruits.findOne(query, options);
console.log(fruit);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
When I ran this app.js using node, I got { score: 10 }
as expected in my terminal, which left me very much dumbfounded!
After checking up the FAQ section under the Node.js driver page of the documentations, I saw that an option was to explicitly use IPV4 by specifying family: 4 as an option in the MongoClient.
I altered my app.js code to include this option and now when I re-run the 1st set of code at the top of this post, MongoSH detects that the fruitsDB is created and displays it when I run show dbs
.
So my question is: Where did my initial creation of database and insertion of data go to when I did not explicitly specify IPV4 usage? and how do I access these from MongoSH?