-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathcreateUser.js
More file actions
53 lines (44 loc) · 1.49 KB
/
createUser.js
File metadata and controls
53 lines (44 loc) · 1.49 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
const User = require('./models/user');
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const print_error = '\x1b[31m%s\x1b[0m'; // prints string injected in red
const print_success = '\x1b[32m%s\x1b[0m'; // prints string injected in green
function getInfoAndCreate() {
rl.question('Please enter the username : ', (username) => {
rl.question('Please enter the password : ', (password) => {
const newUser = User({
user : username,
password : password
});
User.createUser(newUser, function(error){
if (error) {
switch (error.code) {
case 11000: {
console.log(print_error, 'User with provided name already exists! Try again with different name!');
getInfoAndCreate();
return;
}
default: {
throw error;
}
}
} else {
console.log(print_success, "User with username " + newUser.user + " created.");
rl.close(process.exit(1));
}
});
});
});
}
getInfoAndCreate();