I am trying to register a user and save the user to MongoDB. I am creating the user using nodejs readline
module. But when I am trying to save it to the mongodb it is not working. Nor does it is returning any error
.
Here's the code
const { Admin, validate } = require('../models/admin');
const mongoose = require('mongoose');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const print_error = '\x1b[31m%s\x1b[0m';
const print_success = '\x1b[32m%s\x1b[0m';
function createUser() {
rl.question('Please Enter Username : ', (username) => {
rl.question('Please Enter a Password : ', async(password) => {
const adminObject = {
username,
password
};
const { error } = validate(adminObject);
if (error) {
rl.close()
rl.removeAllListeners()
return console.log(print_error, error.details[0].message);
}
let admin = await new Admin({
username: username,
password: password
});
console.log(admin);
const result = await admin.save(function(err,res){
if(err){
console.log('err',err);
return console.log('err',err);
}
else return console.log('res', res);
}); // save is not working
console.log(print_success, result);
rl.close(process.exit(1)); // close the process after done saving
});
});
}
createUser();
Admin Model
const mongoose = require('mongoose');
const Joi = require('joi');
const Admin = new mongoose.model('Admin', new mongoose.Schema({
username: {
type: String,
required: true,
minlength: 1,
maxlength: 10,
unique: true
},
password: {
type: String,
required: true,
minlength:3,
maxlength: 1024
}
}));
function validateAdmin(admin){
const schema = {
username: Joi.string().min(1).required(),
password: Joi.string().min(3).required()
};
return Joi.validate(admin, schema);
}
exports.Admin = Admin;
exports.validate = validateAdmin;
P.S - I've connected to the mongodb, the connection is successful.
I don't know why you're use
async/await
and then you usefunction
in yoursave
.
You can change your createUser
function with this code below:
function createUser() {
rl.question('Please Enter Username : ', (username) => {
rl.question('Please Enter a Password : ', async(password) => {
const { error } = validate({ username, password });
if (error) {
rl.close()
rl.removeAllListeners()
return console.log(print_error, error.details[0].message);
}
let admin = new Admin({username, password });
try {
const result = await admin.save();
console.log(print_success, result);
rl.close(process.exit(1));
} catch(ex) {
console.log(ex.message);
}
});
});
}
If you've any problem, then let me know in the comment below.
Updated: After test your code, you have no connection in your createUser.js
.
I've been add this connection below in above of your createUser()
and it's working:
mongoose.connect('mongodb://localhost:27017/url-shortener');
Please, make sure you've add a connection to your
mongodb
.
I hope it can help you.