Rumah > Soal Jawab > teks badan
使用 Node.js + express + MongoDB 搭建RESTful API服务。
现在遇到的问题是:数据库连接成功后,无法读取集合Collection
内容。
app.js
var express = require('express');
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/db/workflow');
db.connection.on("error", function (error) {
console.log("数据库连接失败:" + error);
});
db.connection.on("open", function () {
console.log("------数据库连接成功!------");
});
var bodyParser = require('body-parser');
var app = express();
// uncomment after placing your favicon in /public
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(require('node-compass')({mode: 'expanded'}));
app.use(express.static(path.join(__dirname, 'public')));
require('./models/group_model');
require('./routes/group')(app);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
models/group_model.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var groupSchema = new Schema({
name:'string'
});
module.exports = mongoose.model("group",groupSchema);
routes/group.js
var express = require('express');
module.exports = function (app) {
var group = require('../controllers/group_controller');
app.get('/group/get',group.getGroup);
};
controllers/group_controller.js
var mongoose = require('mongoose');
var group = mongoose.model('group');
exports.getGroup = function (req, res) {
group.find({}).exec(function (err, data) {
if(!data){
res.json({code: 404, msg: "Empty"});
}else{
res.json({code: 0, msg: "success", data: data, count: data.length});
}
});
};
访问 http://localhost:3000/group/get
返回结果:
{
code: 0,
msg: "success",
data: [ ],
count: 0
}
正常的结果应该是:data
中存在数据。
请各路高手赐教...
黄舟2017-04-17 15:19:55
你确认你库里面的collection(你的应该是groups)里面真的有数据,mongo连上去看一下
你的mongo链接URL我真的没看明白mongodb://localhost/db/workflow 我也想知道这个链接db/workflow的含义????库的名字含有/? 我的理解不应该是mongodb://localhost/workflow,如果你的库的名字是workflow。如果我错了请指出来。
我这边测试是可以取到数据的,最开始是空和你一样,我本地的mongo库里面没有数据,我手动insert进去几条数据,并修改了一下mongo链接,到默认的test库,看了groups collection里面的数据是可以取出来的。