简体   繁体   中英

Im trying to update a users information using MongoDB and JWT

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM