2017-01-28 2 views
0

こんにちは、私はバックエンドノードアプリケーションを初めて使用しています。スクリプトとpugテンプレートエンジンで作業することで、フレームワークなしでクリーンなAPIドリブンnode.jsアプリケーションを作成しようとしています。Node、Express、Pugを使用した動的CRUD関数

私は必要なすべてのコードでserve.jsファイルを作成しました:

var express = require('express'); 
var app = express(); 
var path = require('path'); 
var favicon = require('serve-favicon'); 
const bodyParser = require("body-parser"); 
var mongodb = require("mongodb"); 
const MongoClient = require('mongodb').MongoClient 
var ObjectID = mongodb.ObjectID; 
var indexRoutes = require('./routes/index'); 
var thePort = process.env.PORT || 5000; 


var SECTIONS_COLLECTION = "sections"; 

//make results available as json 
app.use(bodyParser.json()); 

//External database identifier 
var db; 

//Path to the database with URI 
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:[email protected]:19986/heroku_fmvc5nhk'; 

// Connect to the database before starting the application server. 
mongodb.MongoClient.connect(dbpath, function (err, database) { 
    if (err) { 
    console.log(err); 
    process.exit(1); 
    } 

// Save database object from the callback for reuse. 
db = database; 
console.log("Database connection ready"); 

//static folder directory 
app.use(express.static(__dirname + '/dist')); 

// Initialize the app. 
var server = app.listen(process.env.PORT || thePort, function() { 
    var port = server.address().port; 
    console.log("App now running on port", port); 
    }); 
}); 

// Generic error handler used by all endpoints. 
function handleError(res, reason, message, code) { 
    console.log("ERROR: " + reason); 
    res.status(code || 500).json({"error": message}); 
} 


//set up routes directory 
app.use('/', indexRoutes); 

// Views and Template Engine 
//app.set('views', __dirname + './views'); 
app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'pug'); 


// sections API ROUTES: 

/* "/api/sections" 
* GET: finds all sections 
* POST: creates a new contact 
*/ 

app.get("/api/sections", function(req, res) { 
    db.collection(SECTIONS_COLLECTION).find({}).toArray(function(err, docs) { 
    if (err) { 
     handleError(res, err.message, "Failed to get sections."); 
    } else { 
     res.status(200).json(docs); 
    } 
    }); 
}); 

app.post("/api/sections", function(req, res) { 
    var newContact = req.body; 

    if (!req.body.name) { 
    handleError(res, "Invalid user input", "Must provide a name.", 400); 
    } 

    db.collection(sections_COLLECTION).insertOne(newContact, function(err, doc) { 
    if (err) { 
     handleError(res, err.message, "Failed to create new contact."); 
    } else { 
     res.status(201).json(doc.ops[0]); 
    } 
    }); 
}); 

/* "/api/sections/:id" 
* GET: find contact by id 
* PUT: update contact by id 
* DELETE: deletes contact by id 
*/ 

app.get("/api/sections/:id", function(req, res) { 
    db.collection(SECTIONS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) { 
    if (err) { 
     handleError(res, err.message, "Failed to get contact"); 
    } else { 
     res.status(200).json(doc); 
    } 
    }); 
}); 

app.put("/api/sections/:id", function(req, res) { 
    var updateDoc = req.body; 
    delete updateDoc._id; 

    db.collection(SECTIONS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) { 
    if (err) { 
     handleError(res, err.message, "Failed to update contact"); 
    } else { 
     updateDoc._id = req.params.id; 
     res.status(200).json(updateDoc); 
    } 
    }); 
}); 

app.delete("/api/sections/:id", function(req, res) { 
    db.collection(SECTIONS_COLLECTION).deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) { 
    if (err) { 
     handleError(res, err.message, "Failed to delete contact"); 
    } else { 
     res.status(200).json(req.params.id); 
    } 
    }); 
}); 

を私のviews\about.pugテンプレートでは、私は私のJSONオブジェクトの内容を参照します。私のルートで

//--about.pug 
extends index.pug 

block div.root 
    h2= #{about.heading} 
    h3= #{about.summary} 
    p #{about.content} 

routes/index.js I有しパグと既存の "フラット" の例その後つの動的about例:

var express = require('express'); 
var router = express.Router(); 
    router.get('/', function (req, res) { 
     res.render(
      'index', 
      { 
       title: 'Welcome to Awesome Place', 
       header: 'Home', 
       summary: 'This is my home. It can\'t be any simpler' 
      } 
     ) 
    }) 

動的例:

//About 
     router.get('/about', function (req, res) { 
      //retrieve all home from Mongo 
      db.collection(SECTIONS_COLLECTION).find({"name": "about"}), function (err, about) { 

       if (err) { 
       handleError(res, err.message, "Failed to get sections."); 
       } else { 
        res.render('about', {}) 
        console.log(result) 
       } 

      } 
      }) 

上記返しますdb is not definedエラー。

var indexRoutes = require('./routes/index');がserver.jsファイルの一部として必要な場合、なぜdbの値が見つからないのですか?

更新されたコード(エラーが多すぎる)

//server.js

//APP Dependences 
var express  = require('express'); 
var app   = express(); 
var path   = require('path'); 
var favicon  = require('serve-favicon'); 
var indexRoutes = require('./routes/index'); 
var bodyParser = require("body-parser"); 

//PORT 
var thePort = process.env.PORT || 5000; 

// Views and Template Engine 
//app.set('views', __dirname + './views'); 
app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'pug'); 

//Documents 
app.use(bodyParser.json()); 
//static folder directory 
app.use(express.static(__dirname + '/dist')); 


//set up routes directory 
app.use('/', indexRoutes); 

// Catch errors 
app.use(function(req, res, next) { 
    res.status(404).sendFile(process.cwd() + '/app/views/404.htm'); 
}); 


// Initialize the app. 
var server = app.listen(process.env.PORT || thePort, function() { 
    var port = server.address().port; 
    console.log("App now running on port", port); 
    }); 
}); 

var mongodb = require("mongodb"); 
const MongoClient = require('mongodb').MongoClient 
var ObjectID = mongodb.ObjectID; 


var SECTIONS_COLLECTION = "sections"; 



//External database identifier 
var db; 

//Path to the database with URI 
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:[email protected]:19986/heroku_fmvc5nhk'; 

// Connect to the database before starting the application server. 
mongodb.MongoClient.connect(dbpath, function (err, database) { 
    if (err) { 
    console.log(err); 
    process.exit(1); 
    } 

// Save database object from the callback for reuse. 
db = database; 
console.log("Database connection ready"); 


// Initialize the app. 
var server = app.listen(process.env.PORT || thePort, function() { 
    var port = server.address().port; 
    console.log("App now running on port", port); 
    }); 

// Generic error handler used by all endpoints. 
function handleError(res, reason, message, code) { 
    console.log("ERROR: " + reason); 
    res.status(code || 500).json({"error": message}); 
} 

//db.js

var express  = require('express'); 
var mongodb  = require("mongodb"); 
var MongoClient = require('mongodb').MongoClient 
var ObjectID  = mongodb.ObjectID; 
var assert  = require('assert'); 

//Path to the database with 
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:[email protected]:19986/heroku_fmvc5nhk'; 

//Get the section 
var SECTIONS_COLLECTION = "sections"; 

// Use connect method to connect to the server 
var database; 

function connectMongo(cb){ 
    MongoClient.connect(dbpath , function(err, database) { 
     assert.equal(null, err); 
     console.log("Connected successfully to server"); 

     cb(database); 
    }); 
} 

module.exports = connectMongo; 

//routes/index.js

var express  = require('express'); 
var router  = express.Router(); 
var connectDB  = require ('../db') 




    router.get('/', function (req, res) { 
     res.render(
      'index', 
      { 
       title: 'Welcome to Awesome Place', 
       header: 'Home', 
       summary: 'This is my home. It can\'t be any simpler' 
      } 
     ) 
    }) 

connectMongo(function(database){ 
    //About 
     router.get('/about', function (req, res) { 
      //retrieve all home from Mongo 
      database.collection(SECTIONS_COLLECTION).find({"name": "about"}), function (err, about) { 

       if (err) { 
       handleError(res, err.message, "Failed to get sections."); 
       } else { 
        res.render('about', {}) 
        console.log(result) 
       } 

      } 
      }) 
    } 


    router.get('/work', function (req, res) { 
     res.render(
      'work', 
      { 
       title: 'Work, Work, Work , Work...', 
       header: 'Work life', 
       summary: 'My first work for this bitch', 
       imgUrl: '/img/firaz.jpg' 
      } 
     ) 
    }) 

    router.get('/contact', function (req, res) { 
     res.render(
      'contact', 
      { 
       title: 'Contact Me Any Time', 
       header: 'Contact Me Any Time', 
       summary: 'Fill the form below to be contacted' 
      } 
     ) 
    }) 
module.exports = router; 
+0

の可能性のある重複した[ルート/ index.jsにapp.jsから変数を渡す方法?](http://stackoverflow.com/questions/20712712/how-to-pass-variable-from-app -js-to-routes-index-js) –

答えて

0

db変数はrequiriによってグローバルではないためng var indexRoutes = require( './ routes/index');別の方法ではなく、ルート/インデックスファイルからサーバーにオブジェクトをインポートしています。あなたは何ができるか

は、あなたのデシベル変数グローバルglobal.dbを作り、どこでもそれにアクセスしたり、モンゴのDB接続のための別々のファイルを作成し、ルートにこのgithubのレポはのための良好な構造を持っ

var MongoClient = require('mongodb').MongoClient 
    , assert = require('assert'); 

    // Connection URL 
    var url = 'mongodb://localhost:27017/database'; 

    // Use connect method to connect to the server 
    var database; 

    function connectMongo(cb){ 
     MongoClient.connect(url, function(err, db) { 
      assert.equal(null, err); 
      console.log("Connected successfully to server"); 

      cb(db); 
     }); 
    } 

    module.exports = connectMongo; 

を提出することを要求していますMongoDBの https://github.com/OmarElGabry/chat.io

+0

上記はdbがconnectMongo関数の中で動作するのでしょうか? – HGB

+0

connectMongo(function(db){//これを呼び出す場所にdbオブジェクトを取得します}を呼び出すときはyesです。 リポジトリを確認してくださいもっと共有されたmongodb接続構造 –

+0

最も簡単な修正はdb変数のグローバル化です –

関連する問題