【问题标题】:How to update many documents on mongo and return that updated document?如何更新 mongo 上的许多文档并返回更新后的文档?
【发布时间】:2021-10-28 21:43:18
【问题描述】:

如何更新 mongoose 上的许多文档并返回这些更新的文档,以便我可以将更新的文档传递给我的代码上的不同服务?这看起来很简单,但我对如何实现它感到困惑

在我当前的代码中,我只是使用 updateMany 批量更新文档,但正如 mongo 文档所说,返回的 writeConcern 只是更新的文档数 {n: 0 } 不是实际文件。

当前代码:

const checkAndUpdateSubscription = () => {
  const filter = {
    "payments.0.stripeSubscriptionEndDate": { $lte: today },
    hasPaid: true,
  };
  const update = { $set: { hasPaid: false, isSubscriptionNew: 0 } };
  const options = { new: true, useFindAndModify: false };

  return new Promise((resolve, reject) => {
    ModelModel.updateMany(filter, update, options)
      .then((response) => {
        console.log('response inside checkAndUpdateSubscription', response)
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

我想把它改成类似于下面我的伪代码的东西。

我想做的事:

const checkAndUpdateSubscription = () => {
  const filter = {
    "payments.0.stripeSubscriptionEndDate": { $lte: today },
    hasPaid: true,
  };
  const update = { $set: { hasPaid: false, isSubscriptionNew: 0 } };
  const options = { new: true, useFindAndModify: false };

  return new Promise((resolve, reject) => {
    // 1. ModelModel.find where stripeSubscriptionEndDate $lte than today ..etc
    // 2. Update the document(s) 
    // 3. Return the updated document(s)
    (//4.) .then(updatedModel => sendUpdateModelToOutsideService(updatedModel))

  });
};

我不知道在这个问题的上下文中这是否有必要,但checkAndUpdateSubscription 方法是一个函数,它在我的数据库中每 1 分钟为我的所有用户运行一次 (# ~thousands)

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以将这些作为替代解决方案
    (也许有更简单的方法,但我认为这些方法会起作用)

    查找 ID

    • 找到那些id
      ids = find(your_filter,project_keep_id_only),然后制作ids=[_id1, _id2 ...] an array of the ids
    • 使用过滤器 _id 更新 $in ids
      update({"_id" : {"$in" : ids}},your_update_set_etc)
    • 查找获取更新文档
      docs=find({"_id" : {"$in" : ids}})

    *如果 id 不是太多,我认为会很好

    用额外的字段标记更新

    • 在更新时设置一个带有 update_id 的额外字段
    • 更新后,根据 update_id 进行查找,获取文档
    • 如果您希望在之后删除该额外字段

    如果并行运行,这个额外的字段可能是一个数组,其中包含许多 update_id,您在取回这些文档后将其删除。

    【讨论】:

    • 我有点明白你想说什么,但我在update with filter _id $in ids 部分迷路了。您能否详细说明一些代码示例?抱歉,我仍在努力提高我的 mongo 技能。谢谢。
    • 我更新了答案,做起来很简单,只是你发送更多的查询
    • 感谢@Takis_,您的意见帮助很大。按照你的解释,我设法解决了。
    猜你喜欢
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2011-05-21
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多