Im trying to update a users information using MongoDB and JWT - node.js

when I use this code to try and update the user it appears as a server error. Im using JWT and mongodb but am unsure if im pulling the token or the id to update the users information. Below my controller code is attached and my schema.
const updateUser = async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.user.id)
if(!user) return res.status(400).send({ error: 'User not found'})
Object.assign(user, req.body);
user.save()
res.send({ data: user})
} catch (error) {
res.status(500).send({error: 'Server Error'})
}
}
const mongoose = require('mongoose');
let userSchema = new mongoose.Schema({
name: { type: String, required: true},
email: { type: String, required: true, unique: true},
password: { type: String, required: true},
date: { type: Date, default: Date.now}
})
module.exports = mongoose.model('user', userSchema)
Updated update function but i appear to have an error
const updateUser = async (req, res) => {
try {
const updatedUser = await User.findByIdAndUpdate(req.params.id,req.body)
if(!updatedUser) return res.status(400).send('User cannot be updated!')
res.json(updatedUser)
} catch (error) {
res.status(500).send({error: 'Server Error'})
}
}

Try this :
//update user by id
exports.updateUser = async (req, res) => {
try {
const updatedUser = await
<--req.params.id is the user.id and req.body contains the requested fields to update -->
User.findByIdAndUpdate(req.params.id,req.body)
res.json(updatedUser);
}
catch (err) {
console.log(err);
res.status(500).json({ message: 'Internal server error' });
}
}

Related

I'm not sure how to delete a user using MongoDB

I'm trying to be able to delete a user if they choose to delete their account. I'm not sure how it's properly done. Here's the code for the delete function. I've looked at other StackOverflow solutions but I haven't been able to grasp the concept just yet. can anyone help?
const { validationResult } = require('express-validator')
const User = require('../modelSchema/User')
const mongo = require('mongodb')
const signUp = (req, res) => {
const errors = validationResult(req)
if(!errors.isEmpty()) return res.status(400).json({ errors: errors.array()})
//new instance of user
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password })
//save the user
user.save()
.then(data => {
res.json(data)
res.send('User added successfully!')
console.log(data)
})
.catch(err => {
res.status(400).json(err)
})
}
const deleteUser = (req, res) => {
let id = req.params.id;
User.get().createCollection('user', function ( col) {
col.deleteOne({_id: new mongo.ObjectId(id)});
});
res.json({ success: id })
res.send('User Deleted Successfully!')
.catch(err => {
res.status(400).json(err)
})
}
module.exports = { signUp, deleteUser }
here are the routes that I'm using
const express = require('express');
const { check } = require('express-validator')
const { signUp, deleteUser } = require('../controllers/users');
const router = express.Router();
router.post('/signup', [
check('name', 'Please Enter your Name').not().isEmpty(),
check('email', 'Please Enter your Email').isEmail(),
check('password', 'Please Enter your Password').isLength({ minLength: 6})
], signUp)
router.delete('/delete/:id', deleteUser)
module.exports = router;
and here's my schema
const mongoose = require('mongoose');
let 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}
})
module.exports = mongoose.model('user', userSchema)
Update your delete function as below
const deleteUser = async (req, res) => {
const { id } = req.params;
const user = await User.findByIdAndDelete(id);
if (!user) {
return res.status(400).json("User not found");
}
res.status(200).json("User deleted successfully");
};
findByIdAndDelete takes an ObjectId of a user to be deleted. If the user exist, it'll delete the user and return user document, else return null;

Pass a Button value and Update the database

Working on a personal project, one of the functions of the project is to update the user status on what event they are participating.
i wanted to submit a value using a button
<form action="/users/fooddrivebanner" method="POST"><button name="fooddrive" type="submit" value="fooddrive" id="fooddrive">Participate</button></form>
then pass the value to my route and save it inside my database
router.post('/fooddrivebanner', (req,res)=>{
const { fooddrive } = req.body;
const _id = ObjectId(req.session.passport.user._id);
User.findOne({ _id: _id }).then((user)=>{
if (!user) {
req.flash("error_msg", "user not found");
res.redirect("/fooddrivebanner");
}
if (typeof eventparticpating !== "undefined") {
user.eventparticpating = 'fooddrive';
}
user.save(function (err, resolve) {
if(err)
console.log('db error', err)
// saved!
});
})
.catch((err) => console.log(err));
Here is the User model
const mongoose = require('mongoose');
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
},
eventparticpating: {
type: String,
default: 'None At The Moment'
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
It showed a console error
TypeError: Cannot set property 'eventparticpating' of null
UPDATE
Edit 1:
I followed Mr Gambino instructions, error Gone yet cannot update the database, how would i be able to adjust and find my user?
Instead of saving within the findOne function,you can do this:
router.post('/fooddrivebanner', async (req,res) => {
const { fooddrive } = req.body;
const _id = ObjectId(req.session.passport.user._id);
await User.findOne({ _id: _id }, (error, user) => {
if (error) {
req.flash("error_msg", "user not found");
res.redirect("/fooddrivebanner");
}
}).updateOne({ eventparticpating: "foodrive" });
});
I hope that answers your question

Get timestamps of a newly created mongo document in mongoose (MERN)

I'm working on a twitter clone to learn MERN stack, here's a new tweet route
router.route('/new')
.post( (req, res) => {
const { errors, isValid } = validateTweet(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
let tweet = new Tweet({
content: req.body.content,
created_by: req.user.id
})
User.findById(req.user.id, (err, user) => {
if (err) return res.status(400).json(err)
user.tweets.push(tweet._id);
user.save();
});
tweet.save();
return res.status(201).json(tweet);
});
Which does not return timestamps for the tweet, how can i achieve this without querying the database for the tweet before returning it?
Here's the model just in case:
const tweetSchema = new Schema({
content: {
type: String,
required: true,
minlength: 1,
maxlength: 128,
trim: true
},
created_by: {
type: Schema.Types.ObjectId, ref: 'User',
required: true
}
}, {
timestamps: true
});
const Tweet = mongoose.model('Tweet', tweetSchema);
What i ended up doing was making the funcion async then returning the result of the fulfilled save(). Not sure if this is a good practice or not.
router.route('/new')
.post( async (req, res) => {
const { errors, isValid } = validateTweet(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
let tweet = new Tweet({
content: req.body.content,
created_by: req.user.id
})
User.findById(req.user.id, (err, user) => {
if (err) return res.status(400).json(err)
user.tweets.push(tweet._id);
user.save();
});
tweet = await tweet.save();
return res.status(201).json(tweet);
});

How to delete comment that is inside of Post schema?

I'm working on social network app where user can make post and comment. I'm trying to delete comment that is inside of a post. I work with MERN (mongoose, express, react, nodejs). I can successfully delete post, but don't know how to delete its comment.
This is my Mongo connection:
const db = config.get('mongoURI') mongoose.connect(db,{useNewUrlParser: true,useUnifiedTopology: true})
.then(() => console.log('Connected to MongoDB.'))
.catch(err => console.log('Fail to connect.', err))
this is Post Schema
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const PostSchema = new Schema({
userID: {
type: Schema.Types.ObjectId,
ref: 'user'
},
content: {
type: String,
required: true
},
registration_date: {
type: Date,
default: Date.now
},
likes: [
{
type: Schema.Types.ObjectId,
ref: "user"
}
],
comments: [
{
text: String,
userID: {
type: Schema.Types.ObjectId,
ref: 'user'
}
}
]
})
module.exports = User = mongoose.model('posts', PostSchema)
and here is where i tried to delete it:
router.delete("/comment/:postId/:commentId", auth, function (req, res) {
Post.findByIdAndUpdate(
(req.params.postId),
{ $pull: { comments: req.params.commentId } },
{ new: true }
)
.then(post => console.log(post)
.then(() => {
res.json({ success_delete: true })
})
.catch(() => res.json({ success_delete: false })))
});
Well, I think you are creating an app named DevConnector. So I wrote code for the same in the past.
router.delete('/comment/:id/:comment_id', auth, async (req, res) => {
try {
const post = await Post.findById(req.params.id);
// Pull out comment
const comment = post.comments.find(
comment => comment.id === req.params.comment_id
);
// Make sure comment exists
if (!comment) {
return res.status(404).json({ msg: 'Comment does not exist' });
}
// Check user
if (comment.user.toString() !== req.user.id) {
return res.status(401).json({ msg: 'User not authorized' });
}
// Get remove index
const removeIndex = post.comments
.map(comment => comment.user.toString())
.indexOf(req.user.id);
post.comments.splice(removeIndex, 1);
await post.save();
res.json(post.comments);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});

Node.js API find a MongoDB Document by passing ObjectID

The following GET ALL route is working. The second route below, I am trying to retrieve a single Employee document by ObjectId. This is not working. Please help. My Employee model is at the bottom.
// Get all Employees
router.get("/", async (req, res) => {
try {
const employees = await Employee.find();
res.json(employees);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// Get Single Employee by ObjectId
router.get("/:id", (req, res) => {
try {
const employees = await Employee.find(id)
res.json(employees);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
const employeeSchema = new mongoose.Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
required: true,
},
fname: {
type: String,
required: false,
},
lname: {
type: String,
required: false,
},
});
use findById(id) or find({_id: id})
https://mongoosejs.com/docs/api.html#model_Model.find

Resources