MongoDB 删除多个文档,其中包含多个字段必须匹配的对象数组。

huangapple go评论119阅读模式
英文:

MongoDB Remove Many Documents with an array of objects where multiple fields must match

问题

我有一个非常具体的问题,并且已经为它编写了代码,它可以工作,只是我不喜欢它,因为在一个 for 循环中使用了 await,这似乎不是一个好的做法,那么有没有更好的方法来做这件事呢?

const deleteDocuments = async (myObjects: Array<MyObject>) => {
  try {
    for (const myObject of myObjects) {
      await MySchema.findOneAndDelete(
        {
          $and: [
            { prop1: myObject.prop1 },
            { prop2: myObject.prop2 },
            { prop3: myObject.prop3 }],
        },
      );
    }
    const updatedDocuments = MySchema
      .find({}, { _id: 0 })
      .sort({ prop1: 1 });
    return updatedDocuments;
  } catch (e) {
    console.log(`意外错误:${(e as Error).message}`);
  }
};

这段代码似乎可以工作,但我不喜欢它,也不知道如何正确编写它。

英文:

So I have a very particular question and have code written for it that works, I just don't like it, since there is an await in a for-loop which seems like bad practise, so is there a better way to do this?

const deleteDocuments = async (myObjects:Array&lt;MyObject&gt;) =&gt; {
  try {
    for (const myObject of myObjects) {
      await MySchema.findOneAndDelete(
        {
          $and: [
            { prop1: myObject.prop1 },
            { prop2: myObject.prop2 },
            { prop3: myObject.prop3 }],
        },
      );
    }
    const updatedDocuments = MySchema
      .find({}, { _id: 0 })
      .sort({ prop1: 1 });
    return updatedDocuments;
  } catch (e) {
    console.log(`Unexpected Error: ${(e as Error).message}`);
  }
};

This code seems to work, but I don't like it and I don't know how to write it properly.

答案1

得分: -1

以下是翻译好的部分:

try {
    const queryArray = myObjects.map((myObject) => ({
      $and: [
        { prop1: myObject.prop1 },
        { prop2: myObject.prop2 },
      ],
    }));
    const deletionData = await MySchema.deleteMany(
      { $or: queryArray },
      { new: true, _id: 0 },
    ).sort({ prop1: 1 });
    if (!deletionData) {
      console.log('删除对象时出现问题');
      return;
    }
    if (deletionData.deletedCount > 1) {
      console.log(`已删除 ${deletionData.deletedCount} 个对象`);
      return;
    }
    console.log('尝试删除对象,但未删除任何对象');
    return;
  } catch (e) {
    console.log(`意外错误: ${(e as Error).message}`);
  }

请注意,我已经将代码部分翻译成中文,并在文本中保留了原始的代码结构。

英文:

ok, for those interested in the future, this is how I solved this (with a bit of help from chatGPT :p)

try {
    const queryArray = myObjects.map((myObject) =&gt; ({
      $and: [
        { prop1: myObject.prop1 },
        { prop2: myObject.prop2 },
      ],
    }));
    const deletionData = await MySchema.deleteMany(
      { $or: queryArray },
      { new: true, _id: 0 },
    ).sort({ prop1: 1 });
    if (!deletionData) {
      console.log(&#39;Something went wrong while deleting objects&#39;);
      return ;
    }
    if (deletionData.deletedCount &gt; 1) {
      console.log(`Deleted ${deletionData.deletedCount} objects`);
      return ;
    }
    console.log(&#39;Tried to delete objects, but none deleted&#39;);
    return ;
  } catch (e) {
    console.log(`Unexpected Error: ${(e as Error).message}`);
  }```

</details>



huangapple
  • 本文由 发表于 2023年3月9日 22:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定