干编码JS和mongoDB查询,删除重复函数



所以我有一个代码块:

Vampire.find({ gender: `f` }, (err, foundVamps) => {
if (err) console.log(err);
console.log(foundVamps);
process.exit();
}) 
// worked
// Select all vamps with over 500 victims
Vampire.find({ victims: { $gt: 500 } }, (err, foundVamps) => {
if (err) console.log(err);
console.log(foundVamps);
process.exit();
}) 
// worked
// Select all vamps with less than or equal to 150 victims
Vampire.find({ victims: { $lte: 150 } }, (err, foundVamps) => {
if (err) console.log(err);
console.log(foundVamps);
process.exit();
}) 

如您所见,对于每个查询,如果错误控制台日志是相同的,如果不是控制台日志相同的变量,有没有办法我可以干代码以节省必须始终键入它的时间? 也许像这样

const quickFn = (...) => (...);

什么的 相比之下,我对 JS 来说相对较新,但必须有一些东西来使这个代码更干燥?任何帮助将不胜感激。

不确定是谁发布了这个答案,因为他们在发布后立即删除了它,但它是:

const quickFn = filter =>  Vampire.find(filter, (err, foundVamps) => {
if (err) console.log(err);
console.log(foundVamps);
// process.exit(); // do you really need this?
});

// Usage
quickFn({ gender: `f` });
// Select all vamps with over 500 victims
quickFn({ victims: { $gt: 500 } });
// Select all vamps with less than or equal to 150 victims
quickFn({ victims: { $lte: 150 } });

我想感谢那个人,因为它非常适合我的需求

我希望这有帮助

let vampire = [{gender: 'f', gt: 500}, 
{gender: 'm', gt: 120},
{gender: 'f', gt: 100},
{gender: 'f', gt: 505}
];

let vampiresF = vampire.filter(x => x.gender == 'f');
console.log(vampiresF);

let vampiresM = vampire.filter(x => x.gender == 'm');
console.log(vampiresM);
let from120to150 = vampire.filter(x => x.gt >= 120 && x.gt <=500);
console.log(from120to150);

最新更新