我是nodejs,mongoDB的新手,我正在编写一个应用程序来处理来自mongoDB中多个集合的数据与不相关的数据。有没有办法避免为我拥有的每个模型或集合编写CRUD函数?我只想编写每个CRUD操作的一个函数,并为不同的集合或模型重用相同的函数。
我在 crudFunctions.js
中有这个 var mongoose = require('mongoose');
var records = mongoose.model('testCollection');
exports.listAllRecords = function (req, res) {
records.find(function (err, docs) {
if (err) throw err;
res.json(docs);
});
在我的 routes.js
中 module.exports = function(app){
var crud = require('../controllers/crudFunctions');
app.route('/api/data')
.get(crud.listAllRecords)
};
上述代码仅适用于一个模型 记录 ,但我希望在我的数据库中为不同的集合设置不同的模型。问题是,如何在我的 routes.js 中使用类似的东西(可能不正确,但我希望你理解这个问题):
module.exports = function(app){
var crud = require('../controllers/crudFunctions');
app.route('/api/data')
.get(crud.customFunction(function(myModel, results)
{
myModel = model;
console.log(reults)
})
其中: myModel 是我想要做一些CRUD和我的一个差异模型的名称 结果是来自db的文档的响应,以防我执行 find() 查询。