根据条件从集合中删除所有文档并创建丢失的文档

时间:2020-08-09 17:27:25

标签: node.js mongodb mongoose

现在这已经是我已经设法实现的事情了,我只是想知道在我刚开始使用Mongoose和MongoDB时,是否有更简单/更好的方法来实现它。

让我们说我在一个集合中有几个包含“名称”字段的文档(希望我的术语正确),像这样:[{Name: "Name1"}, {Name: "Name3"}],让我们称之为NamesConfiguration

现在,我还有一个名称为config的配置数组["Name1", "Name2"]

我的目标是从NamesConfiguration数组中删除config数组中不存在的所有名称,然后从config数组中添加{{ 1}},所以我的最终收藏应该是NamesConfiguration

[{Name: "Name1"}, {Name: "Name2"}]

我只想知道是否有更好,更“正确”的方法来执行该操作。就我而言,即使这可能会影响性能,也根本不会成为问题,因为我的条目永远不会超过10到20。

通过遵循Yousaf的答案解决了该问题:

try {
  const config = ["Name1", "Name2"];
  const NamesConfiguration = await UIConfiguration.find(); // getting all available nameconfigs from the db

  NamesConfiguration.forEach(async (nameConfig) => {
    if (!config.includes(nameConfig.Name)) {  // loop through and delete the ones that are not within the array
      console.log("deleting" + nameConfig.Name);
      await UIConfiguration.findOneAndDelete({ Name: nameConfig.Name });
    }
  });

  // loop through the array and see if the names are present
  config.forEach(async (configName) => {
    let found = NamesConfiguration.find((nameConfig) => nameConfig.Name === configName);

    // create new nameconfig if not found
    if (!found) {
      console.log("Creating" + configName);
      let NameConfigToAdd = new UIConfiguration({
        Name: configName
      });
      await NameConfigToAdd.save();
    }
  });
} catch (e) {
  console.log(e);
}

1 个答案:

答案 0 :(得分:1)

您可以按照以下步骤进行操作:

  1. 删除集合中Name字段的值出现在config数组中的所有文档。

    要删除Name字段值不在config数组中的任何文档,请使用$in$not运算符编写删除查询。

    UIConfiguration.deleteMany({ Name: { $not: { $in: ["Name1", "Name2"] } } });
    
  2. 获取Name数组中存在config字段值的所有文档。您可以使用$in运算符

    来完成此操作
    UIConfiguration.find({ Name: { $in: ["Name1", "Name2"] } });
    
  3. 遍历返回的文档数组,并过滤​​config数组中与任何文档的Name字段值都不匹配的名称字符串。

  4. 最后,使用.insertMany方法在集合的过滤数组中插入所有名称

    UIConfiguration.insertMany([/* filtered name objects */]);  
    

有关上面使用的方法和运算符的更多详细信息,请参见: