Project Description
- Summary: Practice Node.js with MongoDB; implements helper functions to perform basic CRUD operations (see MongoDB.js).
CRUD Functions (one-liners)
createDBConnection: Create and return a newMongoClientfor a given connection string and store it as the most-recent client.connectToDatabase: Ensure the provided client is connected and return the selected database object.insertData: Insert a single document into a collection, adding acreatedAttimestamp.insertManyDocuments: Insert multiple documents into a collection, addingcreatedAtto each.getAllDataByCollection: Return all documents from a collection as an array.getDataById: Find and return a single document by_id, attempting to convert string ids toObjectIdwhen possible.deleteDataById: Delete a single document matching the provided query from a collection.deleteManyByQuery: Delete all documents matching a query from a collection.closeConnection: Close the stored MongoDB client connection if one exists.
Notes on MongoDB client functions used
MongoClient/ import: The code importsMongoClientandObjectIdfrom themongodbpackage to create clients and handle_idconversions.new MongoClient(connectionString, options): Instantiates a client object without connecting yet.client.connect(): Establishes the network connection to MongoDB (the code treats this as idempotent and awaits it when present).client.db(dbName): Returns aDbinstance scoped todbNamefor collection operations.db.collection(name): Returns a collection handle used to perform CRUD operations.collection.insertOne(doc)/insertMany(docs): Insert operations for single and multiple documents respectively.collection.find(query).toArray(): Run a query cursor and materialize results as an array (used to get all documents).collection.findOne(query): Return a single document matching a query (used for getting by id).collection.deleteOne(query)/deleteMany(query): Remove single or multiple documents matching a query.client.close(): Close the active client connection and free resources.ObjectId(value): Convert a string to a MongoDBObjectId(wrapped in try/catch in the code to allow non-ObjectId keys).
Usage (short)
const {
createDBConnection,
insertData,
getAllDataByCollection,
getDataById,
deleteDataById,
closeConnection,
} = require('./MongoDB');
(async () => {
const client = createDBConnection('mongodb://localhost:27017');
const db = 'testdb';
const col = 'items';
await insertData(client, db, col, { name: 'Example' });
const all = await getAllDataByCollection(client, db, col);
const one = await getDataById(client, db, col, all[0]._id);
await deleteDataById(client, db, col, { _id: one._id });
await closeConnection();
})();