I am trying to add registration detail to database. If i was adding only username and password by this then i am able to insert in mongo db but i am trying to insert name, email all thing then they are giving MissingUsernameError.
{
firstName: 'Name',
lastName: 'Last',
email: 'abc#gmail.com',
phone: '1111111111',
password: 'password'
}
{
MissingUsernameError: No username was given
at Promise.resolve.then (C:\Users\Music\web\node_modules\passport-local-mongoose\index.js:231:17)
at process._tickCallback (internal/process/next_tick.js:68:7) name:
'MissingUsernameError', message: 'No username was given' }
app.post("/register", function(req, res) {
console.log(req.body);
var newUser = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
phone: req.body.phone
});
User.register(newUser, req.body.password, function(err, user) {
if (err) {
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function() {
res.redirect("/");
});
});
});
Related
I'm trying to save in 3 schema (User, UserDetail and Team) data in mongo DB simultaneously but I receive an error
(node:14432) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Here's my code
self.createTeam = function (req, res) {
Logger.request(req);
Logger.requestBody(req);
bcrypt.hash(req.body.password, 10, function (err, hash) {
if (err) {
return res.status(500).json({
error: err
})
} else {
req.body.password = hash;
const team = new Teams({
_id: new mongoose.Types.ObjectId(),
domain: req.body.domain,
avatarOriginal: req.body.avatarOriginal,
avatar_180x180: req.body.avatar_180x180,
avatar_180x100: req.body.avatar_180x100,
name: req.body.name,
createdAt: Date.now(),
updatedAt: Date.now()
});
const user = new User({
_id: new mongoose.Types.ObjectId(),
username: req.body.username,
email: req.body.email,
password: hash,
createdAt: Date.now(),
updatedAt: Date.now()
});
const userDetail = new UserDetail({
_id: new mongoose.Types.ObjectId(),
user_id: user._id,
team_id: team._id,
firstName: req.body.firstName,
lastName: req.body.lastName,
createdAt: Date.now(),
updatedAt: Date.now()
})
team.save().then(function (result) {
return user.save();
}).then(function (result) {
return userDetail.save();
}, function (err) {
res.status(500).json({
error: err
});
}).then(function (user) {
Logger.response(req, user);
res.status(200).json({
success: 'New team and user has been created'
})
})
}
})
}
Please help thank you
Whenever I try to execute the below code using POSTMAN, it shows me an error.
I even tried adding the create adapter by using "let create user = await User.create etc.." but it is still showing error.
Code
//Controller file content
module.exports = {
register: function(req, res){
data = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
description: req.body.description
};
console.log(data);
User.create(data)
.fetch()
.exec((err) => {
if(err){return res.serverError(err);}
});
}
I don't understand if the code is wrong or maybe I am missing something. Please help.
You could try:
register: function(req, res){
data = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
description: req.body.description
};
console.log(data);
User.create(data)
.exec((err, user) => {
if(err){return res.serverError(err);}
else {res.send(user)}
});
}
Or:
register: async function(req, res){
data = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
description: req.body.description
};
console.log(data);
const user = await User.create(data)
.intercept(err => new Error(err))
.fetch();
return res.send(user);
}
I have form with the following action
<form action="users/edit/profile/{{user._id}}" method="post">
route.js
router.post('/edit/profile/:id', controllers.updateUserProfile);
and in controller
updateUserProfile: function(req, res){
User.findByIdAndUpdate(req.params.id, { $set: { username: req.body.username, email: req.body.email, first_name: req.body.first_name, last_name: req.body.last_name }}, function (err, user) {
if (err) {
console.log(err);
res.render("editProfile", {user: req.body});
}
res.redirect("/users/me/");
});
},
but when I submit the form I am getting 404 error
I'm using Node.js with Mongoose and Passport trying to get the user to save to the DB but keep encountering the error where No Username was given. I can get it to save if just using using username and password but as soon as I try to add more fields I get the issue. This is the code I have:
app.js
const userSchema = new mongoose.Schema ({
firstname: String,
lastname: String,
username: String,
password: String,
userLevel: {type: Number},
profileImage: String,
title: String
});
//ENABLE PASSPORT LOCAL
userSchema.plugin(passportLocalMongoose, {
selectFields: ' firstname lastname username password userLevel profileImage title'
});
//CREATE NEW model
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.get('/control', (res, req) => {
if (req.isAuthenticated()) {
res.render('control');
} else {
res.redirect('/login')
}
});
app.post("/register", (req, res) => {
User.register(new User(
{firstname: req.body.firstname},
{lastname: req.body.lastname},
{username:req.body.username},
{userLevel: 1},
{profileImage:"not set"},
{title:"not set"}
),
req.body.password,
(err, user) => {
if (err) {
console.log(err);
console.log(req.body.username);
} else {
passport.authenticate('local')(req, res, () =>{
res.redirect('/control');
});
}
});
});
Figured it out! I was using individual objects rather that just the one object :
User.register((
{firstname: req.body.firstname,
lastname: req.body.lastname,
username: req.body.username,
userLevel: 1,
profileImage:"not set",
title:"not set"
}),
req.body.password,
(err, user) => {
if (err) {
console.log(err);
console.log(req.body.username);
} else {
passport.authenticate('local')(req, res, () =>{
res.redirect('/control');
});
}
});
});
I am trying to access the same database/model for a sign-up and sign-in function but everytime I try to run my node app I get this error message "cannot overwrite 'user' model once compiled" here's my code:
//sign-up schema
var Schema = new mongoose.Schema({
_id: String,
name: String,
username: String,
password: String,
age: Number
});
var user = mongoose.model('users', Schema);
//sign-up login
app.post('/new', function(req, res) {
new user({
_id: req.body.email,
name: req.body.name,
username: req.body.username,
password: req.body.password,
age: req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else res.send('Successfully Signed up');
});
});
//login schema
var Schema = mongoose.Schema;
var UserDetail = new Schema({
username: String,
password: String
}, {
collection: 'users'
});
var UserDetails = mongoose.model('users', UserDetail);
//login logic
passport.use(new LocalStrategy(function(username, password, done) {
process.nextTick(function() {
UserDetails.findOne({
'username': username,
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (user.password != password) {
return done(null, false);
}
return done(null, user);
});
});
}));
You can still use the same schema to lookup.
Schema
var Schema = new mongoose.Schema({
_id: String,
name: String,
username: String,
password: String,
age: Number
});
var user = mongoose.model('users', Schema);
Registration
app.post('/new', function(req, res) {
new user({
_id: req.body.email,
name: req.body.name,
username: req.body.username,
password: req.body.password,
age: req.body.age
}).save(function(err, doc) {
if (err) res.json(err);
else res.send('Successfully Signed up');
});
});
Login
passport.use(new LocalStrategy(function(username, password, done) {
process.nextTick(function() {
user.findOne({
'username': username
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (user.password !== password) {
return done(null, false);
}
return done(null, user);
});
});
}));
If you don't want to return the password in the response, just add
delete user.password;
before the callback.