简体   繁体   中英

Exporting controller is not working in nodeJs

I am creating a simple application to display contacts/users from my database. I have done the following based on some reference found in online. I am getting error 'Can't found the module '..path/controller/ContactController'

  1. Is this the proper way to use MVC. Because I found may mays in online to use MVC. Please suggest some example of using MVC in Node js.

app.js

var express = require('express'),
http = require('http'),
path = require('path'),
mongoose = require('mongoose');

var  app = express();
mongoose.connect("mongodb://localhost/contact");

app.use(express.bodyParser());
app.use(express.bodyParser());
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/view');
app.set('view engine', 'jade');

var controllerPath = __dirname + '/controller';

require('./models/contact')(mongoose);
['Contact'].forEach(function(controller){
require(controllerPath + '/' +  controller +  'Controller')(app, mongoose);
});

http.createServer(app).listen(3000, function() {
console.log('Listening on port 3000...')
})

controller/contact.js

var Contact = require('../models/Contact');
var ContactController = function(app,mongoose){
var Contact = mongoose.model('Contact');
app.get('/contact', function(req, req){
    Contact.find({},function(err, contactinfo){

         res.render("contact",{contact: contactinfo });
    });
})
}
module.exports = ContactController;

models/contact.js

var mongoose = require('mongoose');
var ContactSchema = new mongoose.Schema({
cid: String,
name: String,
phon: Number,
contactwith: String

});
module.exports = mongoose.model('Contact', ContactSchema);

package.json

{
  "name": "SimpleAuth",
   "version": "0.0.1",
   "private": true,
    "scripts": {
      "start": "nodemon app.js"
       },
    "dependencies": {
        "express": "3.0.0rc4",
         "jade": "*",
          "mongoose": "*",
          "nodemon": "*"
         }
      }

You require a wrong path.

require(controllerPath + '/' +  controller +  'Controller')(app, mongoose);

This concatenation doesn't match with this file name : controller/contact.js

Change forEach loop as follows

['contact'].forEach(function(controller){
  require(controllerPath + '/' +  controller)(app, mongoose);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM