【发布时间】:2020-08-10 03:25:19
【问题描述】:
现在这是我已经设法实现的东西,我只是想知道是否有更简单/更好的方法来实现它,因为我刚刚开始使用 Mongoose 和 MongoDB。
假设我在一个集合中有几个具有名称字段的文档(我希望我的术语正确),例如:[{Name: "Name1"}, {Name: "Name3"}],我们称之为NamesConfiguration。
现在我还有一个配置数组config,名称为:["Name1", "Name2"]。
我的目标是从NamesConfiguration 中删除所有在config 数组中不存在的名称,然后从config 数组中添加所有在NamesConfiguration 中不存在的名称,所以我的最终集合应该是[{Name: "Name1"}, {Name: "Name2"}]。
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);
}
我只是想知道是否有更好、“更合适”的方式来执行该操作。在我的情况下,即使这可能会影响性能,它也不会成为一个问题,因为我永远不会有超过 10-20 个条目。
按照优素福的回答解决了这个问题:
const availableConfigs = (await UIConfiguration.find()).map(
(availableConfig) => {
return availableConfig.Name;
}
);
const configNamesToAdd = robotsNames
.filter((robotName) => !availableConfigs.includes(robotName))
.map((configName) => {
return {
Name: configName
};
});
const deleteCondition = {
Name: { $not: { $in: robotsNames } },
};
await UIConfiguration.deleteMany(deleteCondition);
await UIConfiguration.insertMany(configNamesToAdd);
【问题讨论】: