db.collection中的db是未定义的,我无法弄清楚原因

时间:2016-04-06 16:23:06

标签: node.js mongodb

这是我的server.js文件。在我的get'/'路由中,我一直没有定义db。我试图从mongodb集合发布检索文档,并最终让用户能够使用文档键:value查询数据库。有什么想法吗?

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var mongoose = require('mongoose');

mongoose.connect('mongodb://<dbuser>:<dbpassword>@ds061355.mlab.com:61355/db');

app.use(bodyParser.urlencoded({extended: true}))

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});



app.get('/:name', (req, res) => {
    var cursor = db.collection('materials').find();
    db.collection('materials').find().toArray(function(err, results) {
        console.log(results);
    });

});

app.listen(3000, () => {
    console.log('Running app.js on 3000');
});

1 个答案:

答案 0 :(得分:0)

调用connection方法后,必须使用mongoose对象的error属性。如果出现错误,您还应该监听open之类的事件,并且open知道连接成功建立的时间。只有在var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var mongoose = require('mongoose'); mongoose.connect('mongodb://<dbuser>:<dbpassword>@ds061355.mlab.com:61355/db'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log("Connected Successfully."); app.use(bodyParser.urlencoded({extended: true})); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); app.get('/:name', (req, res) => { var cursor = db.collection('materials').find(); db.collection('materials').find().toArray(function(err, results) { console.log(results); }); }); app.listen(3000, () => { console.log('Running app.js on 3000'); }); }); 连接后才能继续。所以你的代码应该是这样的:

{{1}}