简体   繁体   English

mongodb/mongoose 中的保存方法

[英]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.在另一个控制器 (createRoom) foundUser.save() 中它可以工作,但在这个控制器中它没有。 Thanks in advance!提前致谢!

I am using mongodb/mongooose and express.我正在使用 mongodb/mongooose 和 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". Mongoose 做了一些优化,它只会在字段“更改”时才实际保存它。 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.现在,当您保存 Mongoose 时,会看到一个“新”数组,它!== (不等于)前一个数组,因为它是一个新实例,它将保存它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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