Created
December 21, 2021 10:02
-
-
Save FeezyHendrix/4dc12d5e57e92611767147c899e2a215 to your computer and use it in GitHub Desktop.
Create Super User Node.js MongoDB
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 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