-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo_test.js
34 lines (25 loc) · 918 Bytes
/
mongo_test.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
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
async function connectToMongoDB() {
const client = new MongoClient(url, { useNewUrlParser: true });
try {
await client.connect();
console.log('Connected to MongoDB');
const db = client.db(dbName);
var name = 'user' + Math.floor(Math.random() * 10000);
var email = name + '@mit.edu';
var collection = db.collection('customers');
var doc = { name, email };
const result = await collection.insertOne(doc);
console.log('Document inserted with _id:', result.insertedId);
const customers = await collection.find().toArray();
console.log('Collection:', customers);
} catch (error) {
console.error('Error connecting to MongoDB:', error);
} finally {
await client.close();
console.log('Disconnected from MongoDB');
}
}
connectToMongoDB();