update User information mongoose, MongoDB, NodeJS - node.js

I am working on an edit-profile page and i want to change/update the information of the documents in my mongooseDB, but my code does not update the document. Any suggestions?
router.get('/edit', isAuthenticated, function (req, res, next) {
res.render('profile/editprofile', {
user: req.user
});
});
router.post('/edit', isAuthenticated, function (req, res, next) {
User.update({_id: req.session.passport.user.id}, {
email: req.body.email,
password: req.body.password,
name: req.body.name,
phone: req.body.phone,
classc: req.body.classc,
//graduated: req.body.graduated;
major: req.body.major,
minor: req.body.mino,
linkedin: req.body.linkedin,
bio: req.body.bio
}, function (err){
if (err) console.log(err);
res.render('profile/profile', {
user: req.user
});
});
});

You have forgotten to add $set operator
router.post('/edit', isAuthenticated, function (req, res, next) {
console.log(req.user._id) //console like this
User.update({_id: req.user._id}, {$set: req.body}, function (err){
if (err) console.log(err);
res.render('profile/profile', {
user: req.user
});
});
});

Related

im trying to pull the current user's data only from my mongodb to use in ejs file for a profile route where it should be custom to each user's inputs

want this to render the currentusers user.object
app.get("/profile", isLoggedIn, (req,res)=>{
User.find({}, (err,User)=>{
if(err){
console.log(err);
res.redirect("/login");
}else{
res.render("pages/userprofile", {User:User});
console.log(User);
}
})
});
this is my user schema
const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
const UserSchema = new mongoose.Schema({
username: String,
password: String,
review: {
type: mongoose.Schema.Types.ObjectId,
ref: "Review"
}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
when i run the code going to the profile route, it brings back all the users and I have tried multiple ways to only bring back one but I keep getting error
You may consider using findById(id) since the Mongoose documentation suggested to use it than findOne({ _id: id }).
app.get("/profile", isLoggedIn, (req, res) => {
User.findById(req.user, (err, User) => {
if (err) {
console.log(err);
res.redirect("/login");
} else {
res.render("pages/userprofile", { User: User });
console.log(User);
}
})
});
You just have to use findOne for getting one user.
app.get("/profile", isLoggedIn, (req,res)=>{
User.findOne({}, (err,User)=>{
if(err){
console.log(err);
res.redirect("/login");
}else{
res.render("pages/userprofile", {User:User});
console.log(User);
}
})
});
app.get("/profile", isLoggedIn, (req,res)=>{
User.findOne({_id: req.user}, (err,User)=>{
if(err){
console.log(err);
res.redirect("/login");
}else{
res.render("pages/userprofile", {User:User});
console.log(User);
}
})
});
I tried the findOne({...}... and it worked!!!! thank you for the help

Why can't I authenitcate a registered user for this simple MEAN app?

First of all, let me give you a warm thank you for giving a thought to this question.
So, what's the problem?
(This is a simple problem for most of you grandmasters!)
Well, the user can be registered to this simple app. But, for some reason, authentication doesn't work. That some reason is what my brain nerves having a hard time comprehending!
Having tried all the possible solutions for hours and hours, this novice-newbie decided to head over to the haven of veterans here in the StackOverflow!
Let me give you the code, so you can shed me some bright light!
Following is a capture of the code written for the authentication
//Authenticating the user
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
User.getUserByUsername(username, (err, user) => {
if (err) throw err;
if (!user) {
return res.json({
sucess: false,
msg: 'There is no such user found here'
});
}
User.comparePassword(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
const token = jwt.sign(user.toJSON(), config.secret, {
expiresIn: 604800 // 1 week
});
res.json({
success: true,
token: 'JWT' + token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
});
} else {
return res.json({
success: false,
msg: 'Enter the correct details!'
});
}
});
});
});
//Getting into the dashboard
router.get('/profile', passport.authenticate('jwt', {
session: false
}),
(req, res, next) => {
res.json({
user: req.user
});
});
The next few pictures on your way shows you the POSTMAN requests that are done by this novice.
Here, a post request is done to register the user and as you can see, there's not a smidgen of a problem there; the user is, without a doubt, registered!
Here's the authentication done with POSTMAN
But now, for some reason (which I have zero clue of), the user is NOT authenticated. This is the problem that I need to solve.
Here is a code of the model/user.js file in case you want to know what's in there as well
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
// These are the collection or entities in ERD language
const UserSchema = mongoose.Schema({
name: {
type: String
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
const User = module.exports = mongoose.model('user', UserSchema); //User is the name give for this particular model's schema
// these are functions implemented to do a certain task
module.exports.getUserById = function (id, callback) {
User.findById(id, callback);
}
module.exports.getUserByUsername = function (username, callback) {
const query = {
username: username
}
User.findOne(query, callback);
}
module.exports.addUser = function (newUser, callback) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save(callback);
});
})
}
//comparing the hash password
module.exports.comparePassword = function (candidatePasword, hash, callback) {
bcrypt.compare(candidatePasword, hash, (err, isMatch) => {
if (err) throw err;
callback(null, isMatch);
});
}
Thank You for your time!
Stay safe btw!
edit1: The code for the registration or signing up.
router.post('/signup', (req, res, next) => {
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
//console.log("registration is working");
if (err) {
res.json({
sucess: false,
msg: 'Hey! Enter the correct information man!'
});
} else {
res.json({
success: true,
msg: 'you are registered'
});
}
});
});
Here's the whole routes/users.js file for you to refer
const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const config = require('../config/database');
// Signingup the user
router.post('/signup', (req, res, next) => {
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
//console.log("registration is working");
if (err) {
res.json({
sucess: false,
msg: 'Hey! Enter the correct information man!'
});
} else {
res.json({
success: true,
msg: 'you are registered'
});
}
});
});
//Authenticating the user
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
User.getUserByUsername(username, (err, user) => {
if (err) throw err;
if (!user) {
return res.json({
sucess: false,
msg: 'There is no such user found here'
});
}
User.comparePassword(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
const token = jwt.sign(user.toJSON(), config.secret, {
expiresIn: 604800 // 1 week
});
res.json({
success: true,
token: 'JWT' + token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
});
} else {
return res.json({
success: false,
msg: 'Enter the correct details!'
});
}
});
});
});
//Getting into the dashboard
router.get('/profile', passport.authenticate('jwt', {
session: false
}),
(req, res, next) => {
res.json({
user: req.user
});
});
router.post('/login', (req, res, next) => {
let newUser = new User({
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
if (err) {
res.json({
success: false,
msg: "Enter the correct information"
});
} else {
res.json({
success: true,
msg: "User loggedIn"
});
}
});
});
module.exports = router;
In your schema, you don't have the field username but your query is {username: username}. That's why you can't find any user match and get the response "There is no such user found here". Change your query to {name: username} may solve the problem.

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

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

need to delete an element from array nodejs and mongodb

how do i delete a productid say 5bbee0b7e5fcb61df834f7d6 from this arrat have tried
router.post('/empty-cart', isLoggedIn, function(req, res, next) {
console.log("user" + req.body.user + ",product" + req.body.productId);
slug = req.body.productId;
user = req.body.user;
User.findOne({ _id: user }, {
$pull: { productId: slug }
}, function(err, model) {})
console.log(slug);
meanlogger.log('trash', 'Emptied cart', req.user);
res.redirect('/shopping-cart');
});
but seems like it wont apply for arrays as it considers only 1st element looking for suggestions
You cannot use $pull with findOne you should to use update
router.post('/empty-cart', isLoggedIn, function(req, res, next) {
console.log("user" + req.body.user + ",product" + req.body.productId);
slug = req.body.productId;
user = req.body.user;
User.update({ _id: user }, { $pull: { productId: slug } }, function(err, model) {
console.log(slug);
meanlogger.log('trash', 'Emptied cart', req.user);
res.redirect('/shopping-cart');
})
});
this is the correct way.
There is another way. You should find document first, then pull by ObjectId.
router.post('/empty-cart', isLoggedIn, function (req, res, next) {
console.log('user' + req.body.user + ',product' + req.body.productId);
const slug = mongoose.Types.ObjectId(req.body.productId);
const user = req.body.user;
User.findOne({ _id: user }, function (err, model) {
if (err) return res.redirect('/error-page');
if (!model) return res.redirect('/notfound-page');
model.productId.pull(slug);
model.save(function (err) {
if (err) return res.redirect('/error-page');
console.log(slug);
meanlogger.log('trash', 'Emptied cart', req.user);
res.redirect('/shopping-cart');
});
});
});

PassportJS: Edit user info

I'm using PassportJS. I'm trying to let users edit their email address if needed. This is the code I have which is currently not working.
Any advice? Thank you!
app.post("/editprofile", middleware.isLoggedIn, function(req, res, next){
User.update({ id: req.session.passport.user }, {
email: req.body.email,
}, function(err, user) {
if (err) return next(err);
User.findById(req.user._id, function(err, user) {
if (err) return next(err);
console.log(err)
return res.render('landing.ejs', {
user:user
});
});
});
});
Consider using this and every thing will be fine
app.post("/editprofile", middleware.isLoggedIn, function(req, res, next){
User
.findOneAndUpdate({ _id: request.session.passport.user }, req.body.email)
.exec(function(err, user) {
if (err) return res.render(/* Your error template here */, {
err: err.message
};
return res.render('landing.ejs', {
user: user
});
});
}
}
Hope this helps!

Resources