node.js - 如何为数据库查询创建动态辅助函数

标签 node.js mongodb express parse-platform

我有一个类别列表,需要从应用程序中多个位置的数据库中进行选择。

到目前为止,我一直在每次使用时将查询放入回调链中。

我想将它放在一个位置,这样如果我需要修改它,它就是干的。

基本上:

function() {
    var categoryList = {};
    var Category = Parse.Object.extend("Category");
    var categoryQuery = new Parse.Query(Category);
    categoryQuery.find(function(categories) {

        categories.forEach(function(item) {
            item=item.toJSON();
            categoryList[item.objectId] = item.Name;
        });

    });

    return categoryList;
}

但我不确定将其放置在哪里,并且我意识到它在类别列表中的写入方式将是空的。如何创建一个辅助函数来为我提供可以在任何地方使用的结果?

我想我可以将它放在外部文件中并使用 require,但我尝试了:

module.exports = {};
module.exports = function(fn) {

    <code>

    fn['categoryList'] = categoryList;

    return fn;
}(module.exports);

但这似乎不起作用。我将 require 放入 app.js 中,每次包含它时,解析都会显示“更新失败,无法加载触发器。”

我很困惑,而且对 Node/解析很陌生。有人可以帮忙吗?

谢谢。

最佳答案

选项 1

helper.js

var lib = require('lib');

// exports functions
exports.help_a = function (...) { };
exports.help_b = function (...) { };

app.js

// imports heplers functions
helper = require('./helper.js');

//call
helper.help_a(...);
helper.help_a(...);
<小时/>

选项 2

helper.js

// exports module as function
module.exports = function (...) { };

app.js

helper = require('./helper.js');
helper(...);

关于node.js - 如何为数据库查询创建动态辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20557658/

相关文章:

javascript - 尝试使用 mongoose/mongodb-native 执行 mongodb 查询时出现 RangeError

node.js - 从 Angular 4 升级到 5 : "NodeInvocationException: No provider for PlatformRef!"

MongoDb 在 NestJs 中的变更流

javascript - Mongoose 错误 : Schema hasn't been registered for model when populate

node.js - 为什么 Next.js 将静态文件作为参数传递给 url?

jquery - 运行node.js里程表中间件

javascript - 如何使用 NodeJS 发送带有文件名和文件扩展名的文件流

node.js - 如何在nodejs中实现curl u选项

node.js - Express路由器调用错误的路由

MongoDB - 打开和关闭连接 - 建议好的做法