【发布时间】:2017-12-11 05:38:50
【问题描述】:
我正在使用 Node.js、Express 和 Mongoose/MongoDB 构建一个 Web 应用程序。
我遇到的一个问题是如何正确组织和构建与 Mongoose 相关的方法。我需要在我的路由中调用 Mongoose 功能,但所有示例都显示使用 Mongoose 调用,而无需使用原型构建单独的文件或类。
IE。设置架构并在路由中调用 mongoose
SiteModel.find({}, function(err, docs) {
if (!err){
console.log(docs);
process.exit();
} else {throw err;}
});
我想将 mongoose CRUD 函数放在与逻辑和功能相关的帮助文件中,并在我的路由中调用它们。当我对 mongoose 使用单独的类方法时,没有返回值(或者由于异步性质我无法使用结果)
//Router file
var myService = require('../helpers/ServiceStatus');
router.get('/', authService.isLoggedIn, function(req,res){
var serviceObject = new myService(); //Initialize class with Mongoose functions
async.parallel({
modelAFind: function(cb){
//Mongoose class method is called
var response= serviceObject.getAllServiceDetails();
cb(null, response);
},
modelBFind: function(cb){
cb(null, 2); //filler
}
}, function(results){
console.log("Results of query: " + results);
});
来自我创建服务对象的 Mongoose 类的片段:
//ServiceStatus.js
//Constructor
function ServiceStatus() {
}
ServiceStatus.prototype.getAllServiceDetails = function(){
var query = SiteModel.find({});
var promise = query.exec();
promise.then(function (doc) {
return doc;
});
};
处理异步的最佳方法是什么,使用 Mongoose 逻辑构建单独的帮助文件并在路由中调用它们:promise、带有回调的函数等?谢谢。
*编辑 - 添加架构文件
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// set up a mongoose model
module.exports = mongoose.model('SiteModel', new Schema({
id: String,
service: {type: String, unique: true, required: true},
status: String,
settings: Object,
lastCheck: String
}
,{
timestamps: true
}));
【问题讨论】:
标签: javascript node.js express mongoose