MissingUsernameError: No username was given - Unsure where i'm going wrong - node.js

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');
});
}
});
});

Related

Serializing and Deserializing other than user model

I have two schemas one for farmers and other for users but when serializing it is not working..
when in the registered all of the data goes to the Users model
const farmerSchema = new mongoose.Schema({
username: String,
password: String
});
farmerSchema.plugin(passportLocalMongoose);
const Farmer = mongoose.model("Farmer", farmerSchema);
passport.use(Farmer.createStrategy());
passport.serializeUser(Farmer.serializeUser());
passport.deserializeUser(Farmer.deserializeUser());
const userSchema = new mongoose.Schema({
username: String,
password: String,
pattam: [{
name: {
type: String,
unique: true
},
latitude: String,
longitude: String,
pattamdetails: String,
pattamamount: String,
pattamimg: {
data: Buffer,
contenttype: String
}
}]
});
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
//in the register route
app.post("/register", function(req,res){
const farmerOrNot = req.body.radio;
if(farmerOrNot === "yes"){
Farmer.register({username: req.body.username},
req.body.password, function(err,farmer){
if(err){
console.log(err);
res.redirect("/register");
}else{
passport.authenticate("local")(req, res, function(){
res.redirect("/farmersPage");
});
}
});
}
else{
User.register({username: req.body.username},
req.body.password, function(err,user){
if(err){
console.log(err);
res.redirect("/register");
}else{
passport.authenticate("local")(req, res, function(){
res.redirect("/usersPage");
});
}
});
}
});
I want there to be different collections and for each of them to serialize and deserialize ..
Im new to development so don't know if there is any wrong

can I make Passport.js add new field to new register accounts?

i have this code:
i want to have another fields with the user like their phone number, but I don't know how I can add them
const userSchema = new mongoose.Schema({
username: String,
password: String
//// here i want to add another property
});
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model('user', userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
and my registering is this:
User.register({ username: req.body.username }, req.body.password, function (err) {
if (err) {
console.log(err);
res.redirect("/register");
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/");
});
}
});
I don't know where to add the new field
You're almost there! I would recommend to add the field within your schema.
const userSchema = new mongoose.Schema({
username: String,
password: String
phoneNumber: String,
});
Then on your register call you will pass the data into the User.register method.
const user = {
username: req.body.username,
phoneNumber: req.body.phoneNumber,
}
User.register(new User(user), req.body.password, function (err) {
// your callback logic

Cannot understand what create adapter is Sailsjs expecting

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);
}

How can i access values from database

How can i access for example username and put it in profile page ?
model/db.js
const mongoose = require('mongoose');
const stDB = mongoose.Schema({
username : {
type: String,
required: true
},
email : {
type: String,
required: true
},
password : {
type: String,
required: true
}
});
module.exports = mongoose.model('db', stDB);
views/profiles/instructor.hbs
<h5>I want access username from db and put it here!</h5>
index.js
const users = require('../model/db'); // db that username stored in it (model/db.js)
//instructor
router.get('/profiles/instructor', function (req, res, next) {
res.render('./profiles/instructor', {
title: 'Instructor'
});
});
router.post('/signup', function (req, res, next){
const newUser = new users({
username : req.body.username,
email : req.body.email,
password : req.body.password,
});
users.findOne({email : req.body.email}, (err, doc)=>{
if(err){
console.log('ERR while getting username =>' + err);
return ;
}
if(doc){
res.send('this email is already registered before!');
return ;
}
newUser.save((err, doc)=>{
if(err){
console.log('err' + err)
}else{
console.log(doc)
res.redirect('/login')
}
});
});
// etc.....

[Mongoose]How can I use the same model twice with two different schemas within app.js

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.

Resources