我正在使用NodeJS和Restify创建RESTful API。我有以下文件夹结构:
main.js modules
./modules:
continents countries
./modules/continents:
controller.js model.js
./modules/countries:
controller.js model.js
不幸的是,国家/地区模块无效。这是我的代码:
我得到一个空白数组。
{
error: false,
data: [ ]
}
main.js
var restify = require('restify');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/app');
var controllers = {};
controllers.continents = require('./modules/continents/controller');
controllers.countries = require('./modules/countries/controller');
var server = restify.createServer();
server
.use(restify.fullResponse())
.use(restify.bodyParser());
// Routes
server.get('/api/continents', controllers.continents.getContinents);
server.get('/api/:continent/countries', controllers.countries.getCountries);
server.listen(3000, function() {
console.log('%s listening at %s', server.name, server.url);
});
国家> controller.js
var mongoose = require('mongoose');
var model = require('./model');
var Countries = mongoose.model('Countries');
exports.getCountries = function(req, res, next) {
console.log("Countries");
Countries.find({link: req.params.continent}, function(err, countries) {
console.log(req.params.continent);
console.log(countries);
if (err) {
res.status(500);
res.json({
error: true,
data: 'Error occured: ' + err
});
} else {
if (countries) {
res.json({
error: false,
data: countries
});
} else {
res.json({
error: true,
data: "Countries for " + req.params.continent + " are not found."
});
}
}
});
};
国家> model.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var CountriesSchema = new Schema({
name: String,
imgSrc: String
});
mongoose.model('Countries', CountriesSchema);