【问题标题】:Mongoose & MongoDB: ignore cast errors when performing a bulkWriteMongoose 和 MongoDB:执行 bulkWrite 时忽略转换错误
【发布时间】:2022-11-18 12:16:32
【问题描述】:

我正在尝试使用 MongoDB 中支持的 bulkWrite 操作将数据导入到我的应用程序的数据库中。由于它来自外部来源,因此数据中可能存在错误。这就是为什么我想更新我的收藏,同时跳过不符合标准的文档,以维护我自己数据的完整性。但是,如果数据不干净并且每当我尝试运行我的代码时更新被阻止,我就会收到转换错误。有人可能会争辩说必须事先清理数据,我同意这一点,但我想确保在忽略错误时我的更新不会崩溃。以下示例代码清楚地说明并复制了我试图避免的错误类型:

const mongoose = require("mongoose");

data = [
  {
    description: "nice product",
    stock: 10,
    product_id: "01"
  },
  {
    description: "useful product",
    stock: "error will be generated",
    product_id: "02"
  }
];

const InventorySchema = new mongoose.Schema({
  description: String,
  stock: Number,
  product_id: {
    type: String,
    unique: true
  }
});
const Inventory = mongoose.model("Inventory", InventorySchema);

upsertData = Inventory.bulkWrite(data.map((product) => {
  try {
    return ({ updateOne: {
      filter: { product_id: product.product_id },
      update: { $set: product },
      upsert: true
    }});
  } catch(e) {
    // Do nothing
  }
}));

mongoose.connection.once("open", () => {
  upsertData;
});

此示例代码将生成以下错误:CastError:转换为数字失败,因为路径“stock”处的值“将生成错误”.更重要的是,该程序甚至不会尝试连接到数据库。我不确定,但 mongoose 似乎在定义 upsertData 函数后立即解析数据。该程序应该遍历来自外部数据的每个文档,并尝试更新内部数据库,同时忽略格式错误的数据。

【问题讨论】:

    标签: javascript node.js mongodb mongoose error-handling


    【解决方案1】:

    我无法直接解决问题,所以我决定采用不同的方法:我没有执行 bulkWrite,而是遍历数据数组并将每个产品的操作分为两部分。 1) 检查是否存在具有相同 ID 的产品,以及 2) 根据第一个条件更新集合或创建新文档。但是,此方法的操作效率不如 bulkWrite。无论如何,我决定分享我的解决方案,以防其他人发现它有用。让我知道你的想法!

    data.map(async (product) => {
      let exists = await Inventory.findOne({ product_id: product.product_id });
      if (exists) {
        // Update document if product exists
        Inventory.updateOne({ product_id: product.product_id }, product)
          .catch((e) => { console.log(e); });
      } else {
        // Create if product does not exist or ignore if data is unclean
        Inventory.create(product).catch((e) => {return});
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-23
      • 2021-07-06
      • 2021-05-11
      • 2017-05-29
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      • 2019-07-13
      相关资源
      最近更新 更多