-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseeder.js
41 lines (33 loc) · 1.07 KB
/
seeder.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
require('dotenv').config();
const MongoClient = require('mongodb').MongoClient;
const fs = require('fs');
const { ObjectId } = require('mongodb');
const uri = process.env.MONGODB_URI;
const dbName = 'Assessment';
const collectionName = 'users';
const dataFilePath = 'users.json';
async function seedUsers() {
let client;
try {
client = await MongoClient.connect(uri, { useUnifiedTopology: true });
console.log('Connected successfully to MongoDB');
const db = client.db(dbName);
const usersCollection = db.collection(collectionName);
const data = await fs.promises.readFile(dataFilePath, 'utf8');
const usersData = JSON.parse(data);
let insertedCount = 0;
for (const user of usersData) {
user._id = new ObjectId(user._id.$oid); // Convert $oid field to ObjectId
await usersCollection.insertOne(user);
insertedCount++;
}
console.log(`Successfully inserted ${insertedCount} users into the database.`);
} catch (err) {
console.error('Error:', err);
} finally {
if (client) {
client.close();
}
}
}
seedUsers();