I have two models in MongooseDB, how do I update the two at once using Node.js and React.js?

I have two models named user and post in my Mongoose database. I will like that when I update the user model, it reflects on the post model. For instance, I updated my username from the user model, I would like that update to take effect on the post model as well. I am using Node.js and React.

enter image description here

here is my code on Node.js for the user model

router.put("/:id", async (req, res) =>{
if(req.body.userId === req.params.id){//we checked if the user id matched
 if(req.body.password){
            const salt = await bcrypt.genSalt(10);
            req.body.password = await bcrypt.hash(req.body.password, salt);
        }
        try{
       const updatedUser = await User.findByIdAndUpdate(req.params.id,{
            
               $set: req.body,
              
               
           }, {new: true}); 
            //findbyidandupdate is an inbuilt method
    
        res.status(200).json(updatedUser)
       
    } catch(err){
    res.status(500).json(err) //this handles the error if there is one from the server
    }
    } else{
    res.status(401).json("You can only update your account!")
   }

  });


from Recent Questions - Stack Overflow https://ift.tt/3BlilO9
https://ift.tt/3gJsjRo

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation