javascript - 干编码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 } });
我想感谢那个人,因为它非常适合我的需要
推荐阅读
- amazon-s3 - 连接到 s3 存储桶时出现 Presto 错误 400
- javascript - Next.js - 如何在带有文字 onload 属性字符串值的内部添加标签?
- swift5 - Xcode 11.6 在导入自定义框架时出错:使用 Swift 5.3 编译的模块无法由 Swift 5.2.4 导入
- javascript - Javascript 中的数据传递问题 - Chrome 扩展
- oracle - 要查找的 Oracle DB 基本信息
- arduino - Arduino 串行比较
- javascript - 错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头 - 如何修复它
- php - 如何从 MySQL 数据库表中复制数据并使用它来更新另一个表
- c# - 使用 C# 从给定的 .dll 注册类型库
- python-3.x - glooey 按钮 (pyglet) 上的图像有时绘制有时不绘制