使用 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
中存在数据。
请各路高手赐教...
你確認你庫裡面的collection(你的應該是groups)裡面真的有數據,mongo連上去看一下
你的mongo連結URL我真的沒看懂mongodb://localhost/db/workflow 我也想知道這個連結db/workflow的意思? ? ? ?庫的名字含有/? 我的理解不應該是mongodb://localhost/workflow,如果你的函式庫的名字是workflow。如果我錯了請指出來。
我這邊測試是可以取到數據的,最開始是空和你一樣,我本地的mongo庫裡面沒有數據,我手動insert進去幾條數據,並修改了一下mongo鏈接,到預設的test庫,看了groups collection裡面的資料是可以取出來的。