且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用updateMany 在猫鼬中返回更新的模型?

更新时间:2023-12-01 13:38:10

我认为更新多个文档并返回所有更新的文档是不可能的.

I don't think it is possible to update multiple documents and return all updated documents.

update()updateMany() 方法更新多个文档并仅返回 WriteResult

update() or updateMany() method updates multiple documents and returns only the WriteResult

如果使用 {new: true} 的 MongoDB 方法的 findAndModify() 更新单个文档,您可以更新文档作为响应.

You can have updated document in response if the single document gets updated using findAndModify() of MongoDB method using {new: true}.

来自文档.

findAndModify:findAndModify 命令修改并返回单个文档.默认情况下,返回的文档不包括对更新所做的修改.返回文件对更新所做的修改,使用新选项.

findAndModify : The findAndModify command modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.

你可以做的是:

再次获取那些更新的文档.

Fetch again those documents which are updated.

const result = await Todo.updateMany(
      { _id: { $in: ids }, userId },
      { $set: { complete } },
      { new: true }
    ).populate('userId', '_id');

// here you can update and then get all documents again
const updatedResult = await Todo.find(
      { _id: { $in: ids }, userId }
    ).populate('userId', '_id');

res.json({ todos: updatedResult });