动态CRUD功能与Node,Express和Pug

时间:2017-01-28 16:10:34

标签: node.js mongodb express pug

您好我是后端节点应用程序的新手,我正在尝试使用脚本和pug模板引擎创建一个没有框架的干净API驱动的node.js应用程序。

我创建了一个包含所有必要代码的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:5rqdhjqc2orjhen7knanjpfmd7@ds014586.mlab.com: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我预先存在"扁平" pug的示例然后是一个动态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错误。

如果我的server.js文件中需要var indexRoutes = require('./routes/index');,为什么它找不到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:5rqdhjqc2ovanbfd7knanjpfmd7@ds019986.mlab.com: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:5rqdhjqc2ovahen7knanjpfmd7@ds019986.mlab.com: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;

//路由/ 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;

1 个答案:

答案 0 :(得分:0)

因为db变量不是全局的,因为要求var indexRoutes = require(' ./ routes / index');您正在将对象从routes / index文件导入到服务器,而不是相反。

你可以做的是让你的db变量全局global.db并在任何地方访问它或为mongo db连接创建一个单独的文件,并要求在路由文件中

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;

这个github Repo为mongoDB提供了良好的结构 https://github.com/OmarElGabry/chat.io