英文:
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<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(`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) => ({
$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('Something went wrong while deleting objects');
return ;
}
if (deletionData.deletedCount > 1) {
console.log(`Deleted ${deletionData.deletedCount} objects`);
return ;
}
console.log('Tried to delete objects, but none deleted');
return ;
} catch (e) {
console.log(`Unexpected Error: ${(e as Error).message}`);
}```
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论