I did the registration portion successfully now I am trying to delete the registered user by id . This is how I did
user controller
const mongoose = require ('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) =>{
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.phoneNumber = req.body.phoneNumber;
user.save((err, doc) =>{
if(!err)
res.send(doc);
else{
if (err.code == 11000)
res.status(422).send(["Entered duplicate email address. Please check"]);
else
return next(err);
}
});
}
And in my index router
const express = require ('express');
const router = express.Router();
const ctrlUser = require ('../controllers/user.controller.js');
// routing functions
router.post('/register' , ctrlUser.register);
router.delete('/:userId' , (req, res, next) =>{
User.remove({_id: req.params.userId})
.exec()
.then(result => {
res.status(200).send(["Deleted"]);
})
.catch(err =>{
if (err.code == 500)
res.status(500).send(["Didn't get deleted"]);
else
return next(err);
});
});
module.exports = router;
When I am testing in postman I am not getting any response. Where did I make the mistake ? Something am I missing out ?
EDIT:- Including user.model
const mongoose = require ('mongoose');
const bcrypt = require('bcryptjs');
//define user schema
var userSchema = new mongoose.Schema({
fullName : {
type: String,
required: "Full name can't be empty"
},
email : {
type: String,
required: "Email can't be empty",
unique: true
},
password : {
type: String,
required: "Password can't be empty",
minlength: [6 ,"Password must be atleast 6 character long"]
},
phoneNumber : {
type: String,
required: "Reqired for further contact.Can't be empty"
},
saltSecret: String //this is user for encryption and decryption of password
});
mongoose.model('User', userSchema);
Related
I´m trying to set up a register and login server with node.js and mongoose. So I have create an user model and an user route. Can someone find the mistake why I can´t create an user. I connect to Postman under POST : localhost:3000/users/register
my user model:
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
minlength: 1,
trim: true, //calls .trim() on the value to get rid of whitespace
unique: true, //note that the unique option is not a validator; we use mongoose-unique-validator to enforce it
},
password: {
type: String,
required: true,
minlength: 8,
},
});
//this enforces emails to be unique!
UserSchema.plugin(uniqueValidator);
//this function will be called before a document is saved
UserSchema.pre('save', function(next) {
let user = this;
if (!user.isModified('password')) {
return next();
}
//we generate the salt using 12 rounds and then use that salt with the received password string to generate our hash
bcrypt
.genSalt(12)
.then((salt) => {
return bcrypt.hash(user.password, salt);
})
.then((hash) => {
user.password = hash;
next();
})
.catch((err) => next(err));
});
module.exports = mongoose.model('User', UserSchema);
my routes user:
const express = require('express');
const bcrypt = require('bcryptjs');
const User = require('../models/user');
const router = express.Router();
//util function to check if a string is a valid email address
const isEmail = (email) => {
if (typeof email !== 'string') {
return false;
}
const emailRegex = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
return emailRegex.test(email);
};
router.post('/register', async (req, res) => {
try {
const { email, password } = req.body;
if (!isEmail(email)) {
throw new Error('Email must be a valid email address.');
}
if (typeof password !== 'string') {
throw new Error('Password must be a string.');
}
const user = new User({ email, password });
const persistedUser = await user.save();
res.status(201).json({
title: 'User Registration Successful',
detail: 'Successfully registered new user',
});
} catch (err) {
res.status(400).json({
errors: [
{
title: 'Registration Error',
detail: 'Something went wrong during registration process.',
errorMessage: err.message,
},
],
});
}
});
router.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
if (!isEmail(email)) {
return res.status(400).json({
errors: [
{
title: 'Bad Request',
detail: 'Email must be a valid email address',
},
],
});
}
if (typeof password !== 'string') {
return res.status(400).json({
errors: [
{
title: 'Bad Request',
detail: 'Password must be a string',
},
],
});
}
//queries database to find a user with the received email
const user = await User.findOne({ email });
if (!user) {
throw new Error();
}
//using bcrypt to compare passwords
const passwordValidated = await bcrypt.compare(password, user.password);
if (!passwordValidated) {
throw new Error();
}
res.json({
title: 'Login Successful',
detail: 'Successfully validated user credentials',
});
} catch (err) {
res.status(401).json({
errors: [
{
title: 'Invalid Credentials',
detail: 'Check email and password combination',
errorMessage: err.message,
},
],
});
}
});
module.exports = router;
my server :
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
const dotenv = require("dotenv");
const app = express();
dotenv.config();
//other imports
const usersRoute = require('./routes/users');
//other app.use statements
//connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true,
useUnifiedTopology: true},
() => console.log('Database connected')
);
mongoose.Promise = global.Promise;
const port = process.env.PORT || 3000;
//sets up the middleware for parsing the bodies and cookies off of the requests
app.use(bodyParser.json());
app.use(cookieParser());
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
module.exports = { app };
what I only get is this.:
Cannot POST /users/register
You didn't specify the path prefix in your server file. You should define:
app.use("/users", usersRoute );
I have creating one ecommerce application, Inside this i have facing some issue regarding req.gravatar() is not a function.
Whenever I have send data through postman give me error, those error I have defined above.
account.js file code
const router = require('express').Router();
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const config = require('../config');
var gravatar = require('gravatar');
router.post('/signup', (req, res, next) => {
let user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
user.picture = req.gravatar();
user.isSeller = req.body.isSeller;
User.findOne({ email: req.body.email }, (err, existingUser) => {
if(existingUser) {
res.json({
success: false,
message: 'Account with that email is already exist'
});
}
else{
user.save();
var token = jwt.sign({
user: user
}, config.secret, {
expiresIn: '7d'
});
res.json({
success: true,
message: 'Enjoy your token',
token: token
});
}
});
});
module.exports = router;
User.js file code
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');
const crypto = require('crypto');
const UserSchema = new Schema({
email: { type: String, unique: true, lowercase: true },
name: String,
password: String,
picture: String,
isSeller: { type: Boolean, default: false },
address: {
add1: String,
add2: String,
city: String,
state: String,
country: String,
postalCode: String
},
created: { type: Date, default: Date.now }
});
UserSchema.pre('save', function(next) {
var user = this;
if(!user.isModified('password')) return next();
bcrypt.hash(user.password, null, null, function(err, hash) {
if(err) return next(err);
user.password = hash;
next();
});
});
UserSchema.methods.comparePassword = function(password) {
return bcrypt.compareSync(password, this.password);
}
UserSchema.methods.gravatar = function(size) {
if(!this.size) size = 200;
if(!this.email) {
return 'https://gravatar.com/avatar/?s' + size + '&d=retro';
}
else{
var md5 = crypto.createHash('md5').update(this.email).digest('hex');
return 'https://gravatar.com/avatar/' + md5 + '?s' + size + '&d=retro';
}
}
module.exports = mongoose.model('User', UserSchema);
please help me to solve this question as fast as possible.
because i am Amateur developer in node.js technology.
In the following line, gravatar is not an attribute of req and therefore cannot be invoked as a function
user.picture = req.gravatar();
I suppose that what you want to do, is something like:
user.picture = gravatar.url(user.email);
With this change, user.picture will contain the URL of the gravatar user profile picture for that email.
I'm new at coding and nodejs and I believe this problem may be just my lack of nodejs/coding experience.
The code is posted below and for more information I have posted the Github file
I am trying to call the object id from one function into another function so I can relate the parent and child functions.
Specifically (in the file users.js) I am trying to calling the newUser variable from the function router.post("/register", (req, res) to the function router.post("/registerCar", (req, res) but whenever I try to call the newUser variable in the registerCar function, it seems to empty. Even if I call User._id, that also seems to be empty.
I am trying to figure out how to call the object id of newUser into newCar.
Things I have tried:
I have tried to add the router.post("/registerCar", (req, res) into the router.post("/register", (req, res) but whenever I try to submit the car registration form it says "method POST registerCar cannot be found" or something of the sort
Made newUser into a global variable, but for some reason I wasn't able to call it in router.post("/registerCar", (req, res)
Tried callback parameter in router.post("/register", (req, res) function but that didn't really work (although I could have been doing it wrong)
I have tried adding _id: Schema.Types.ObjectId; into User.js and Car.js but it gives me an error "Error [MongooseError]: document must have an _id before saving at new MongooseError". I tried researching a solution for this but nothing came up.
I know this is a lot, but I'm trying to expand my coding skills and I've been stuck at this for two days. If you guys can help me out I would greatly appreciate it.
___________________________________________________________________________________________________
// User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
carType: [{
type: Schema.Types.ObjectId,
ref: 'Car'
}]
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
___________________________________________________________________________________________________
//Car.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserModel = new mongoose.Schema({
carMake: {
type: String,
require: true,
},
carModel: {
type: String,
require: true,
},
carid: [{
type: Schema.Types.ObjectId,
ref: 'User'
}]
});
const Car = mongoose.model('Car', UserModel);
module.exports = Car;
___________________________________________________________________________________________________
//users.js
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const passport = require("passport");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// User model
const User = require("../models/User");
//Cars model
const Car = require("../models/Car");
//Login
router.get("/login", (req, res) => res.render("login"));
//Register Page
router.get("/register", (req, res) => res.render("register"));
//test page
router.get("/test", (req, res) => res.render("test"));
//registerCar Page
router.get("/registerCar", (req, res) => res.render("registerCar"));
// Register Handle
router.post("/register", (req, res) => {
const { name, email, password, password2 } = req.body;
let errors = [];
// Check required fields
if (!name || !email || !password || !password2) {
errors.push({ msg: "Please fill in all fields." });
}
// Check passwords match
if (password != password2) {
errors.push({ msg: "Passwords do not match." });
}
// Check pw length
if (password.length < 6) {
errors.push({ msg: "Password should be longer than 6 characters." });
}
// Issue present
if (errors.length > 0) {
res.render("register", {
errors,
name,
email,
password,
password2,
});
} else {
// Validation passed
User.findOne({ email: email }).then((user, callback) => {
if (user) {
// User exists
errors.push({ msg: "Email is already registered" });
res.render("register", {
errors,
name,
email,
password,
password2,
});
} else {
const newUser = new User({
name,
email,
password,
});
// Hash Password
bcrypt.genSalt(10, (err, salt) =>
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
//Set password to hashed
newUser.password = hash;
//Save user
newUser
.save()
.then((user) => {
req.flash(
"success_msg",
"You are now registered. Please log in."
);
res.redirect("/users/login");
})
.catch((err) => console.log(err));
})
);
}
});
}
});
// Login Handle
router.post("/login", (req, res, next) => {
passport.authenticate("local", {
successRedirect: "/dashboard",
failureRedirect: "/users/login",
failureFlash: true,
})(req, res, next);
});
//Logout Handle
router.get("/logout", (req, res) => {
req.logout();
req.flash("success_msg", "You are logged out");
res.redirect("/users/login");
});
// Car registration Handle
router.post("/registerCar", (req, res) => {
const { carMake, carModel, carid } = req.body;
let errors = [];
const newCar = new Car({
carMake,
carModel,
carid, //want to call User ID over here
});
newCar
.save()
.then((car) => {
console.log(newCar._id);
res.redirect("/dashboard");
})
.catch((err) => console.log(err));
});
module.exports = router;
___________________________________________________________________________________________________
github link: https://github.com/AamirAshraf96/carGarage
This question already has answers here:
E11000 duplicate key error index in mongodb mongoose
(22 answers)
Closed 3 years ago.
any time i try to register a user it gives me this error
I checked the db collection and no such duplicate entry exists, let me know what I am doing wrong ?
FYI - req.body.email and req.body.password are fetching values.
I also checked this post but no help STACK LINK
If I removed completely then it inserts the document, otherwise it throws error "Duplicate" error even I have an entry in the local.email
Server started on port 5000
MongoDB Connected
MongoError: E11000 duplicate key error collection: test.users index: email1_1 dup key: { email1: null }
{ driver: true,
name: 'MongoError',
index: 0,
code: 11000,
keyPattern: { email1: 1 },
keyValue: { email1: null },
errmsg: 'E11000 duplicate key error collection: test.users index: email1_1 dup key: { email1: null }',
[Symbol(mongoErrorContextSymbol)]: {}
}
Following is my user schema in user.js model
Schema
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {type: String, unique: true, required: true
},
resetPasswordToken: String,
resetPasswordExpires: Date,
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
Route
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
const async = require("async");
const nodemailer = require("nodemailer");
const crypto = require("crypto");
// Load User model
const User = require('../models/User');
const { forwardAuthenticated } = require('../config/auth');
// Login Page
router.get('/login', forwardAuthenticated, (req, res) => res.render('login'));
// Register Page
router.get('/register', forwardAuthenticated, (req, res) => res.render('register'));
// Register
router.post('/register', (req, res) => {
const { name, email, password, password2 } = req.body;
let errors = [];
if (!name || !email || !password || !password2) {
errors.push({ msg: 'Please enter all fields' });
}
if (password != password2) {
errors.push({ msg: 'Passwords do not match' });
}
if (password.length < 6) {
errors.push({ msg: 'Password must be at least 6 characters' });
}
if (errors.length > 0) {
res.render('register', {
errors,
name,
email,
password,
password2
});
} else {
User.findOne({ email: email }).then(user => {
if (user) {
errors.push({ msg: 'Email already exists' });
res.render('register', {
errors,
name,
email,
password,
password2
});
} else {
const newUser = new User({
name,
email,
password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => {
req.flash(
'success_msg',
'You are now registered and can log in'
);
res.redirect('/users/login');
})
.catch(err => console.log(err));
});
});
}
});
}
});
// Login
router.post('/login', (req, res, next) => {
passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/users/login',
failureFlash: true
})(req, res, next);
});
// Logout
router.get('/logout', (req, res) => {
req.logout();
req.flash('success_msg', 'You are logged out');
res.redirect('/users/login');
});
module.exports = router;
The thing is that, as I see from the error message, it seems like you have one entity in the DB which has no email(basically email = null). And because you've specified email field as unique, mongoDB thinks that not having an email is unique, so there can only be one entity with no email field in the collection. And you're trying to add another entity with no email, and eventually, you have an error, because this entity also has no email as a record in the DB.
You just need to verify if email is present, before sending it to DB, or implement other solution that fits for your business logic.
Hope it helps :)
I am working on a test signup with nodejs, i set up a free mongo lab database and testing signups on my local server. i keep getting this error an on my route, i can console upto var user = new User(); (console- user) and get the objects . I can console user.profile and console will display name and picture as objects etc. but for some reason my code is saying user.profile.name is undefined . Any error you guys can spot ?
this is my model
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;
var UsersSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: String,
profile: {
name: { type: String, default: '' },
picture: { type: String, default: '' }
},
address: String,
history: [{
date: Date,
paid: { type: Number, default: 0 },
}]
});
UsersSchema.pre('save',function(next){
var user = this;
if(!user.isModified('password')) return next();
bcrypt.genSalt(10, function(err, salt){
if(err) return next(err);
bcrypt.hash(user.password,salt, null,function(err,hash){
if (err) return next(err);
user.password = hash;
next();
});
})
})
UsersSchema.methods.comparePassword = function(password){
return bcrypt.compareSync(password, this.password)
}
module.exports = mongoose.model('User',UsersSchema);
this my route file
var router = require('express').Router();
var User = require('../models/users');
// var user = new User();
// console.log('user',user.profile.name);
router.post('/signup', function(req, res, next) {
var user = new User();
user.profile.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
User.findOne({ email: req.body.email }, function(err, existingUser) {
if (existingUser) {
return res.redirect('/signup');
} else {
user.save(function(err, user) {
if (err) return next(err);
res.json("New user has been created");
});
}
});
});
module.exports = router;
//res.json("New user has been created")
You'll have to assign profile to something first as user is defined but user.profile is not
defined user.profile = '' before the line user.profile.name = req.body.name
or replace the following and try
-var User = require('../models/users'); with var UsersSchema = require('../models/users');
-var user = new User(); with var user = new UsersSchema();
You are trying to access name property from profile, which is not defined.
var user = new User();
user.profile.name = req.body.name;
-----------/\
To make this work, first define profile:
var user = new User();
user.profile = {};
user.profile.name = req.body.name;