Home > OS >  Why user.save() is not updating the database?
Why user.save() is not updating the database?

Time:05-05

The database is of the form as shown in the image:

enter image description here

I am trying to update the category field as received from the frontend.

Here is my code:

exports.postCategory= (req, res, next)=>{
    User.findOne({_id: req.userId})
        .then(user=>{
            if(!user){
                const error= new Error('No user found');
                error.statusCode= 422;
                throw error;
            }
            
            user.category.Animal= req.body.Animal;
            user.category.Name= req.body.Name;
            user.category.Place= req.body.Place;
            user.category.Thing= req.body.Thing;
            
            
            return user.save();
        })
        .then(result=>{
            res.status(200).json({message:'Category data refreshed', result: result});
        })
        .catch(err=>{
            if(!err.statusCode){
                err.statusCode= 500;
            }
            next(err); 
        })
}

When I console.log resultI could see that the user's category has been updated but when I view the database there happens to be no change.

Please guide me on how to make changes appear in the database, also let me know if more information is required.

CodePudding user response:

You can simplify your code by using findByIdAndUpdate and async - await.
Also, parameters might be interpret as strings, try to use a condition to convert them to booleans:

exports.postCategory = async (req, res, next) => {
    try {
      const { Animal, Name, Place, Thing } = req.body;
      const updatedUser = await User.findByIdAndUpdate(
        req.userId,
        {
          $set: {
            'category.Animal': Animal && Animal.toString().toLowerCase() === 'true',
            'category.Name': Name && Name.toString().toLowerCase() === 'true',
            'category.Place': Place && Place.toString().toLowerCase() === 'true',
            'category.Thing': Thing && Thing.toString().toLowerCase() === 'true',
          },
        },
        { new: true }
      );
  
      res
        .status(200)
        .json({ message: 'Category data refreshed', result: updatedUser });
    } catch (err) {
      next(err);
    }
  };  

CodePudding user response:

I added user.markModified('category'); above the line return user.save(); and the database started updating.

user.markModified('category') manually set the category column that I was trying to update as modified and this made mongoose to detect the column change and update the database.

Refer to this article for more info:

https://sarav.co/understanding-markModified-in-mongoose#:~:text=markModified(), it manually sets,change and updates the DB.&text=* Marks the path as having,to write to the db.&text=That's it!

  • Related