I'm trying to write MVC in nodejs. The problem is, that render method returns undefined, instead of database data. But if I call
Website.find({}, function(err, docs) {
res.send(`docs`);
})
direct from index.js - it works just fine, am I doing something wrong?
index.js:
app.get('/websites', (req, res) => {
const View = require("./views/websitesView");
const Controller = require("./controllers/websitesController");
const Model = require("./models/websiteModel");
var model = new Model();
var controller = new Controller(model);
var view = new View(controller);
res.send(view.render(req, res));
})
view.js:
var controller = require("../controllers/websitesController");
class websitesView {
controller;
constructor(controller) {
this.controller = controller;
}
setTab(tab) {
this.tab = tab;
}
render(req, res) {
res.send(`${this.controller.getAllWebsites()}`);
}
}
module.exports = websitesView;
controller.js:
const Website = require("../models/websiteModel");
class websitesController {
model;
constructor(model) {
this.model = model;
}
getAllWebsites() {
Website.find({}, function(err, docs) {
return docs;
})
}
}
module.exports = websitesController;
model.js
const mongoose = require("mongoose")
const websiteSchema = new mongoose.Schema({
url: String,
user_id: String,
type: String,
status: Number,
timestamp: Date
}, {collection: "aaa_websites"})
module.exports = mongoose.model("Website", websiteSchema, 'aaa_websites')
Using a Mongoose model defined in another file returns Undefined didn't help
CodePudding user response:
Try this:
index.js:
app.get('/websites', async (req, res) => {
const View = require("./views/websitesView");
const Controller = require("./controllers/websitesController");
const Model = require("./models/websiteModel");
var controller = new Controller(Model);
var view = new View(controller);
res.send(await view.render(req, res));
})
view.js:
var controller = require("../controllers/websitesController");
class websitesView {
controller;
constructor(controller) {
this.controller = controller;
}
setTab(tab) {
this.tab = tab;
}
async render(req, res) {
res.send(`${await this.controller.getAllWebsites()}`);
}
}
module.exports = websitesView;
controller.js:
class websitesController {
model;
constructor(model) {
this.model = model;
}
async getAllWebsites() {
return this.model.find({})
}
}
module.exports = websitesController;