Radek Stared
Radek Stared

Reputation: 23

save method in mongodb/mongoose

This is my first question here. I tried to save document in my collection, but it doesn't work. Response of function is exactly like I want, but it doesn't save in my db. In another controller (createRoom) foundUser.save() it works, but in this controller it doesn't. Thanks in advance!

I am using mongodb/mongooose and express.

const removeRoom = async (req,res,next) => {
   const {roomId, userData} = req.body;
   const { userId, token } = userData;
   
   let foundUser;
   let updatedRooms;
   let indexOfNamespaces;

   try {
      foundUser = await User.findById(userId)
      foundUser.namespaces.forEach((ns,i1)=>{
         updatedRooms = ns.rooms.filter((room,i2) => {
         if(room.id === roomId){
            indexOfNamespaces = i1;
         }
         return room.id !== roomId
      })

   })   
   foundUser.namespaces[indexOfNamespaces].rooms = updatedRooms;
   console.log(foundUser);

   await foundUser.save();
      
   } catch (err) {
      console.log(err);
      
      const error = new HttpError('Sth went wrong [removeRoom]', 500);
      return next(error);
   }
   res.status(201).json({updatedNamespaces: foundUser.namespaces});

}

Upvotes: 0

Views: 94

Answers (1)

CaptEmulation
CaptEmulation

Reputation: 4586

Mongoose does some optimizations where it will only actually save a field if it "changes". In this case you are modifyting an array, but the array is still the "same" array as in it still === (equals) the previous array. You need to use a new array to replace namespaces.

For example:

foundUser.namespaces = [
  ...foundUser.namespaces.slice(0, indexOfNamespaces), 
  { ...foundUser.namespaces[indexOfNamespaces], rooms: updatedRooms }, 
  ...foundUser.namespaces.slice(indexOfNamespaces + 1)
]

Now, when you save Mongoose will see a "new" array that !== (does not equal) the previous array because it is a new instance and it will save it.

Upvotes: 1

Related Questions