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);
}
Related
i am trying to add some data inside my MongoDB database, but i am not able to remove duplicate entries.
please help me to do so.
i am using node js and mongoose.
app.post('/', function (req, res) {
const newUser = new Newsletter ({
fname: req.body.fname,
lname: req.body.lname,
message: req.body.message,
email: req.body.email
});
newUser.save(function (err) {
if (!err) {
res.render("success");
} else {
const errCode = res.statusCode;
res.render("failure", { errStatusCode: errCode });
}
})
})
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("/");
});
});
});
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 update user data in the settings page. Where he/she can change all details like name, last name, birthday and so on. Here is the auth controller:
module.exports = {
async CreateUser(req, res) {
const schema = Joi.object().keys({
username: Joi.string()
.min(4)
.max(10)
.required(),
email: Joi.string()
.email()
.required(),
firstName: Joi.string()
.required(),
lastName: Joi.string()
.required(),
position: Joi.string()
.required(),
password: Joi.string()
.min(5)
.required(),
});
const { error, value } = Joi.validate(req.body, schema);
if (error && error.details) {
return res.status(HttpStatus.BAD_REQUEST).json({ msg: error.details })
}
const userEmail = await User.findOne({
email: Helpers.lowerCase(req.body.email)
});
if (userEmail) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: 'Email already exist' });
}
const userName = await User.findOne({
username: Helpers.firstUpper(req.body.username)
});
if (userName) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: 'Username already exist' });
}
return bcrypt.hash(value.password, 10, (err, hash) => {
if (err) {
return res
.status(HttpStatus.BAD_REQUEST)
.json({ message: 'Error hashing password' });
}
const age = moment().diff(moment([value.byear, value.bmonth - 1, value.bday]), 'years');
const body = {
username: Helpers.firstUpper(value.username),
email: Helpers.lowerCase(value.email),
firstName: value.firstName,
lastName: value.lastName,
position: value.position,
password: hash,
};
User.create(body)
.then(user => {
const token = jwt.sign({ data: user }, dbConfig.secret, {
expiresIn: '5h'
});
res.cookie('auth', token);
res
.status(HttpStatus.CREATED)
.json({ message: 'User created successfully', user, token });
})
.catch(err => {
res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: 'Error occured' });
});
});
},
User model
const userSchema = mongoose.Schema({
username: { type: String },
email: { type: String },
isVerified: { type: Boolean, default: false },
firstName: { type: String },
lastName: { type: String },
position: { type: String },
password: { type: String },
I guess I shoud have a route like this:
router.post('/user/settings', AuthHelper.VerifyToken, user.editUser);
How should it look like editUser controller according to above CreateUser function? I am using Angular in the front-end. But I think it doesn't matter. I assume 90 percent should be the same as CreateUser but what exactly should be changed so the user can update his/her details in settings form and change data in the model?
So you want to update some of user's fields (such as firstName, lastName and etc.), not replacing the whole information. Then you might want to get the current user's data first and then update only those allowed fields.
Please find the sample code below.
/**
* User router
*/
router.put('/user/:userId', AuthHelper.VerifyToken, user.editUser);
// This function will be triggered when Express finds matching route parameter
router.param('userId', function (req, res, next, id) {
User.findOne(id, function (err, user) {
if (err) {
next(err);
} else if (user) {
// When it finds user information, bind that to request object, which will be used in the other middlewares.
req.user = user;
next();
} else {
next(new Error('failed to load user'));
}
});
});
/**
* User controller
*/
exports.editUser = (req, res, next) => {
let { user } = req;
// You pick only allowed fields from submitted body
const allowedFields = { firstName: req.body.firstName, lastName: req.body.lastName, birthday: req.body.birthday };
// Override the current user data with new one
user = Object.assign(user, allowedFields);
user.save((err, savedUser) => {
if (err) {
return next(err);
}
res.json(savedUser.toJSON());
});
};
I´m getting a problem with Mongoose Nodejs
This is my code for Controllers to Insert user in the database using Schema User from imported another file.
router.post('/insert', function insertUsert(req, res){
var newUser = User({
name: req.body.name,
username: req.body.username,
password: req.body.password,
admin: false
});
newUser.save(function(err){
if(err){
res.status(400).send(err);
}else{
res.status(201).send("User Inserted)");
}
})
});
This is my connection Mongoose:
var dbURI = 'mongodb://localhost/trabbel';
if (process.env.NODE_ENV === 'production') {
dbURI = process.env.MONGOLAB_URI || 'mongodb://<>:<>#ds133465.mlab.com:33465/locations';
mongoose.connect(dbURI);
console.log(dbURI);
}
// CONNECTION EVENTS
mongoose.connection.on('connected', function() {
console.log('Mongoose connected to ' + dbURI);
});
When I execute with Postman in the Route:
POST /user/insert - - ms - -
The .connect is inside a condition that runs only on production, turn it to:
if (process.env.NODE_ENV === 'production') {
dbURI = process.env.MONGOLAB_URI || 'mongodb://<>:<>#ds133465.mlab.com:33465/locations';
}
mongoose.connect(dbURI);
console.log(dbURI);
try it
That pass a reference of function in router.post
router.post('/insert', insertUsert);
function insertUsert(req, res, next){
const newUser = new User({
name: req.body.name,
username: req.body.username,
password: req.body.password,
admin: false
})
newUser.save().then(function(user) {
if(err) res.status(400).json({"message": err})
res.status(200).json(user)
})
}
Try using the below code. while inserting, you need to use new keyword
router.post('/insert', function insertUsert(req, res, next){
new User({
name: req.body.name,
username: req.body.username,
password: req.body.password,
admin: false
}).save(function(err, user){
if(err){
return next(err);
}
res.status(201).send("User Inserted)");
})
});
I think this adjustment to your code will make it work. I figured out you forgot the new keyword in creating the instance of your user model. I believe that will fix your problem.
router.post('/insert', function insertUsert(req, res, next){
var newUser = new User({
name: req.body.name,
username: req.body.username,
password: req.body.password,
admin: false
});
newUser.save(function(err){
if(err){
return next(err);
}
res.status(201).send("User Inserted)");
})
});