首页 > 解决方案 > 干编码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 来说是相对较新的东西,但必须有一些东西才能使这个更干燥的代码?任何帮助,将不胜感激。

标签: javascriptmongodb

解决方案


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

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 } });

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


推荐阅读