-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongoclient.js
66 lines (57 loc) · 1.5 KB
/
mongoclient.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* @file mongoClient.js
* @description Simple MongoDB client that writes a record to a local MongoDB database.
* @version 1.0.0
* @date 2023-10-05
* @license MIT
*
* @dependencies
* - mongodb: MongoDB client for Node.js
*
* @usage
* To run the script, use the following command:
* ```
* node mongoClient.js
* ```
*
* @notes
* - Ensure that MongoDB is running locally before running the script.
*
* @maintainer
* - GitHub Copilot
*/
const { MongoClient } = require('mongodb');
// MongoDB connection URI
const uri = 'mongodb://localhost:27017';
// Database and collection names
const dbName = 'mydatabase';
const collectionName = 'mycollection';
// Sample record to insert
const sampleRecord = {
name: 'John Doe',
email: '[email protected]',
age: 30,
createdAt: new Date(),
};
async function writeRecord() {
const client = new MongoClient(uri);
try {
// Connect to MongoDB
await client.connect();
console.log('Connected to MongoDB');
// Get the database and collection
const db = client.db(dbName);
const collection = db.collection(collectionName);
// Insert the sample record
const result = await collection.insertOne(sampleRecord);
console.log(`Record inserted with _id: ${result.insertedId}`);
} catch (error) {
console.error('Error writing record to MongoDB:', error);
} finally {
// Close the MongoDB connection
await client.close();
console.log('MongoDB connection closed');
}
}
// Run the writeRecord function
writeRecord();