Skip to content

Instantly share code, notes, and snippets.

@GeorgianStan
Created February 11, 2020 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeorgianStan/a70687e83a783ae888ba71d31011a4ea to your computer and use it in GitHub Desktop.
Save GeorgianStan/a70687e83a783ae888ba71d31011a4ea to your computer and use it in GitHub Desktop.
Mongodb NodeJS Driver
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