Skip to content

Instantly share code, notes, and snippets.

@FeezyHendrix
Created December 21, 2021 10:02
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 FeezyHendrix/4dc12d5e57e92611767147c899e2a215 to your computer and use it in GitHub Desktop.
Save FeezyHendrix/4dc12d5e57e92611767147c899e2a215 to your computer and use it in GitHub Desktop.
Create Super User Node.js MongoDB
const readline = require('readline');
const mongoose = require('mongoose');
const usermodel = require('../models/users.model');
const bcrypt = require('bcrypt');
const database = process.env.MONGODB_URI || "mongodb://localhost:27017/<inputlocaldb>";
mongoose.connect(database, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});
mongoose.connection.on("connected", () => {
console.log(`Connected to the database ${database}`);
runCreateSuperUser();
});
mongoose.connection.on("error", (err) => {
console.log(err);
throw new Error('CANNOT CONNECT TO DATABASE ERROR');
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const runCreateSuperUser = () => {
rl.question('Email Address: ', (email) => {
rl.question('Password: ', async (password) => {
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(password, salt);
const user = await usermodel.create({
email,
password: hash,
});
if (user) {
console.log('Created succesfully!');
} else {
console.log('Unable to created user!');
}
rl.close();
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment