这是我的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');
});
答案 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}}