使用 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
Confirm that the collection in your library (yours should be groups) really has data in it, connect mongo to take a look
I really don’t understand your mongo link URL mongodb://localhost/db/workflow I also want to know the meaning of this link db/workflow? ? ? ? The name of the library contains /? My understanding should not be mongodb://localhost/workflow, if the name of your library is workflow. Please point it out if I'm wrong.
I can get the data in the test here. It was empty at first. Just like you, there is no data in my local mongo library. I manually inserted a few pieces of data and modified the mongo link. The default test library, after looking at the data in groups collection, can be taken out.