mkdir test-mongodb && cd test-mongo-db npm init
npm install mongodb
Just in case, the script is running under node.js version 20.15 and mongodb module version 6.8 (current on moment of writing). To check the versions:
node -v
and to check the module version use whatever you like
npm info mongodb version npm view mongodb version npm list | grep mongodb
Sorry, it might be looked a little bit messy, but the script provides a connection, up to 4 insertions, retrieval, drop/deletion, and start over.
Source: Node Driver Quick Start
const { MongoClient } = require('mongodb'); // Connection URL with the database name const url = 'mongodb://127.0.0.1:27017/mydb'; // Create a new MongoClient const client = new MongoClient(url); async function main() { try { // Use connect method to connect to the Server await client.connect(); console.log("Connected successfully to server"); const db = client.db('mydb'); const col = db.collection("customers"); // const result = await db.collection("customers").deleteMany(); // Print the number of deleted documents // console.log("Deleted " + result.deletedCount + " documents"); // Print a message if no documents were found if ((await col.countDocuments()) > 4) { const result = await col.deleteMany(); } var myobj = { name: "New name", address: "somebody's address" }; res = await col.insertOne(myobj); console.log(`A document was inserted with the _id: ${res.insertedId}`); // customers = await db.collection("customers").findOne() // console.log(customers); const cursor = col.find(); // Print a message if no documents were found if ((await col.countDocuments()) === 0) { console.log("No documents found!"); } // Print returned documents const results = await cursor.toArray(); console.log(results); // or // for await (const doc of cursor) { // console.log(doc); // } } catch (err) { console.log(err); } finally { await client.close(); } } main();
Pages: 1 2