【发布时间】: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