Created
February 11, 2020 19:26
-
-
Save GeorgianStan/a70687e83a783ae888ba71d31011a4ea to your computer and use it in GitHub Desktop.
Mongodb NodeJS Driver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MongoClient = require("mongodb").MongoClient; | |
(async function() { | |
const newDbName = "my-new-db"; | |
const newDbUser = "test"; | |
const newDbPwd = "test"; | |
const newCollection = "my-new-collection"; | |
// ? Create a new user for a new database | |
console.time("CreateNewUser"); | |
{ | |
const url = "mongodb://admin:admin@localhost:27017/admin"; | |
const client = await new MongoClient(url, { | |
useUnifiedTopology: true | |
}).connect(); | |
await client | |
.db() | |
.admin() | |
.addUser(newDbUser, newDbPwd, { | |
roles: [ | |
{ role: "dbAdmin", db: newDbName }, | |
{ role: "readWrite", db: newDbName } | |
] | |
}); | |
await client.close(); | |
} | |
console.timeEnd("CreateNewUser"); | |
// ? Connect to the new database & collections | |
console.time("CreateNewCollection"); | |
{ | |
console.log("HERE"); | |
const url = `mongodb://${newDbUser}:${newDbPwd}@localhost:27017/admin`; | |
const client = await new MongoClient(url, { | |
useUnifiedTopology: true | |
}).connect(); | |
mongoClient = client; | |
await client.db(newDbName).createCollection(newCollection, { | |
capped: true, | |
size: 1024 | |
}); | |
// await client.db(newDbName).dropDatabase(); | |
await client.close(); | |
} | |
console.timeEnd("CreateNewCollection"); | |
console.time("InsertDocs"); | |
// ? Connect to the new database | |
{ | |
console.log("HERE"); | |
const url = `mongodb://${newDbUser}:${newDbPwd}@localhost:27017/admin`; | |
const client = await new MongoClient(url, { | |
useUnifiedTopology: true | |
}).connect(); | |
mongoClient = client; | |
await client | |
.db(newDbName) | |
.collection(newCollection) | |
.insertMany([{ email: "myemail@email.com" }]); | |
// await client.db(newDbName).dropDatabase(); | |
await client.close(); | |
} | |
console.timeEnd("InsertDocs"); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment