简体   繁体   中英

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

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.

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