node.js无法读取未定义路由的属性'collection'\ index.js:6:11

时间:2018-03-07 22:09:24

标签: javascript node.js

我是node.js的初学者,并尝试构建一个基本的待办事项列表,但不断收到错误:  无法读取undefined的属性'collection'。 有人可以解释我做错了什么以及如何让我的帖子请求有效? 谢谢您的帮助 !

路由/ index.js

var express = require('express');
var router = express.Router();
var ObjectId = require('mongodb').ObjectId
// Get Homepage
router.get('/', ensureAuthenticated, function(req, res){
       req.db.collection('Todo').find().sort({"_id": -1}).toArray(function(err, result) {
        //if (err) return console.log(err)
        if (err) {
            req.flash('error', err)
            res.render('index', {
                title: 'User List', 
                data: ''
            })
        } else {
            // render to views/user/list.ejs template file
            res.render('index', {
                title: 'User List', 
                 data:  'ldld'
            })
        }
    })
})
function ensureAuthenticated(req, res, next){
    if(req.isAuthenticated()){
        return next();
    } else {
        //req.flash('error_msg','You are not logged in');
        res.redirect('/users/login');
    }
}

module.exports = router;

路由/ Todo.js

// list dependencies
var express = require('express');
var router = express.Router();

// add db & model dependencies
var mongoose = require('mongoose');
var Todo = require('../models/Todo');

// interpret GET /products - show product listing */


// GET intepret GET /products/edit/:id - show single product edit form */
router.get('/Todo/edit/:id', function (req, res, next) {
    //store the id from the url in a variable
    var id = req.params.id;
  var user_id = req.cookies ?
      req.cookies.user_id : undefined;
    //use the product model to look up the product with this id    
    Todo.findById(id,user_id, function (err, product) {
        if (err) {
            res.send('Product ' + id + ' not found');
        }
        else {
            res.render('edit', { Todo: Todo });
        }
    });
});

// POST /products/edit/:id - update selected product */
router.post('/Todo/edit/:id', function (req, res, next) {
    var id = req.body.id;

    var Todo = {
        _id: req.body.id,
        content: req.body.content,
        todos   : todos,
         updated_at : Date.now()
    };

    Todo.update({ _id: id}, content, function(err) {
        if (err) {
            res.send('Product ' + req.body.id + ' not updated. Error: ' + err);
        }
        else {
            res.statusCode = 302;
            res.setHeader('Location', 'http://' + req.headers['host'] + '/Todo');
            res.end();
        }
    });
});

// GET /products/add - show product input form
router.get('/Todo/create', function (req, res, next) {
    res.render('add');
});

// POST /products/add - save new product
router.post('/Todo/create', function (req, res, next) {

    // use the Product model to insert a new product
    Todo.create({
       content: req.body.content,
        user_id:req.cookies.user_id,
         updated_at : Date.now()

    }, function (err,Todo) {
        if (err) {
            console.log(err);
            res.render('error', { error: err }) ;
        }
        else {
            console.log('Product saved ' + Todo);
            res.render('added', {Todo: Todo.content });
        }
    });
});

// API GET products request handler
router.get('/api/Todo', function (req, res, next) {
    Todo.find(function (err, products) {
        if (err) {
            res.send(err);
        } 
        else {
            res.send(Todo);
        }
    });
});

/* GET product delete request - : indicates id is a variable */    
router.get('/Todo/delete/:id', function (req, res, next) {
    //store the id from the url into a variable
    var id = req.params.id;

    //use our product model to delete
    Todo.remove({ _id: id }, function (err,Todo) {
        if (err) {
            res.send('Product ' + id + ' not found');
        }
        else {
            res.statusCode = 302;
            res.setHeader('Location', 'http://' + req.headers['host'] + '/Todo');
            res.end();
        }
    });
});

// make controller public
module.exports = router;

视图/ index.handelbars

 <h2 class="page-header">Dashboard</h2>

 <p> Hello {{user.name}}
<p>Welcome to your dashboard</p>  




<% layout( 'layout' ) -%>

<h1 id="page-title">{{ title }}</h1>

<div id="list">
  <form action="/create" method="post" accept-charset="utf-8">
    <div class="item-new">
      <input class="input" type="text" name="content" />
    </div>
  </form>

  {{#each todo}}
  <div class="item">
    <a class="update-link" href="/edit/{{#todo._id }}" title="Update this todo item">{{todo.content}}</a>
    <a class="del-btn" href="/destroy/{{ #todo._id }}>" title="Delete this todo item">Delete</a>
  </div>
{{/each }}

app.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');
var Todo = require('./routes/Todo');

// Init App
var app = express();

// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');

// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));

// Express Session
app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: true
}));

// Passport init
app.use(passport.initialize());
app.use(passport.session());

// Express Validator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));

// Connect Flash
app.use(flash());

// Global Vars
app.use(function (req, res, next) {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  res.locals.user = req.user || null;
  next();
});



app.use('/', routes);
app.use('/users', users);
app.use('/Todo', Todo);

// Set Port
app.set('port', (process.env.PORT || 3000));

app.listen(app.get('port'), function(){
    console.log('Server started on port '+app.get('port'));
});

1 个答案:

答案 0 :(得分:0)

var app = express();

之后立即将以下内容添加到app.js
app.use(function (req, res, next) {
  req.db = db;
  next();
});

这将在所有传入请求中创建对您的猫鼬连接的引用,可通过req.db访问。