我目前正在使用Simon Holmes的这本名为 getting-MEAN 的书来学习MEAN堆栈,我遇到了一个问题,书中说标题中提到的请求应该返回一个回复,应该是一个完整的位置对象,存储在我的MongoDB中。
然而它只是加载很长时间并输出Postman output 我想,因为这本书使用了较旧的环境,所以我的环境版本搞砸了?
我的环境:
✗uname-srmo
Linux 4.11.6-3-ARCH x86_64 GNU / Linux
✗节点--version
V8.1.2
✗表达 - 版本
4.15.0
✗mongod--version
db版本v3.4.3
git版本:f07437fb5a6cca07c10bafa78365456eb1d6d5e1
OpenSSL版本:OpenSSL 1.1.0f 2017年5月25日
allocator:tcmalloc
模块:无
建设环境:
distarch:x86_64
target_arch:x86_64
✗npmlist mongoose
loc8r@0.0.1 / home / username / github / Loc8r
└──mongoose@3.8.40
var mongoose = require ('mongoose');
var Loc = mongoose.model ('Location');
var sendJsonResponse = function (res, status, content){
res.status (status);
res.json (content);
};
module.exports.locationsCreate = function (req, res) {
sendJsonResponse (res, 200, {"status" : "Create success"});
};
module.exports.locationsListByDistance = function (req, res) {
sendJsonResponse (res, 200, {"status" : "ListByDist success"});
};
module.exports.locationsReadOne = function (req, res) {
Loc
.findById (req.params.locationid)
.exec (function (err, location){
sendJsonResponse (res, 200, location);
});
};
module.exports.locationsUpdateOne = function (req, res) {
sendJsonResponse (res, 200, {"status" : "success"});
};
module.exports.locationsDeleteOne = function (req, res) {
sendJsonResponse (res, 200, {"status" : "success"});
};

var express = require ('express');
var router = express.Router ();
var ctrlLocations = require ('../controllers/locations');
var ctrlReviews = require ('../controllers/reviews');
//locations
router.get ('/locations', ctrlLocations.locationsListByDistance);
router.post ('/locations', ctrlLocations.locationsCreate);
router.get ('/locations/:locationid', ctrlLocations.locationsReadOne);
router.put ('/locations/:locationid', ctrlLocations.locationsUpdateOne);
router.delete ('/locations/:locationid', ctrlLocations.locationsDeleteOne);
//reviews
router.post ('/locations/:locationid/reviews', ctrlReviews.reviewsCreate);
router.get ('locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsReadOne);
router.put ('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsUpdateOne);
router.delete ('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsDeleteOne);
module.exports = router;

var mongoose = require('mongoose');
var gracefulShutdown;
var dbURI = 'mongodb://localhost/Loc8r';
if (process.env.NODE_ENV === 'production') {
console.log ("NODE ENVIROMENT: "+ process.env.NODE_ENV);
dbURI = process.env.MONGODB_URI;
}
mongoose.connect(dbURI);
// CONNECTION EVENTS
mongoose.connection.on('connected', function() {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error', function(err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function() {
console.log('Mongoose disconnected');
});
// CAPTURE APP TERMINATION / RESTART EVENTS
// To be called when process is restarted or terminated
gracefulShutdown = function(msg, callback) {
mongoose.connection.close(function() {
console.log('Mongoose disconnected through ' + msg);
callback();
});
};
// For nodemon restarts
process.once('SIGUSR2', function() {
gracefulShutdown('nodemon restart', function() {
process.kill(process.pid, 'SIGUSR2');
});
});
// For app termination
process.on('SIGINT', function() {
gracefulShutdown('app termination', function() {
process.exit(0);
});
});
// For Heroku app termination
process.on('SIGTERM', function() {
gracefulShutdown('Heroku app termination', function() {
process.exit(0);
});
});
// BRING IN YOUR SCHEMAS & MODELS
require('./locations');

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
require('./app_api/models/db');
var routes = require('./app_server/routes/index');
var routesApi = require ('./app_api/routes/index');
// var users = require('./app_server/routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// tells the application to check the server application routes
// for all incoming requests
app.use('/', routes);
app.use ('/api', routesApi);
// app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;

var mongoose = require('mongoose');
...
...
var locationSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
address: String,
rating: {
type: Number,
"default": 0,
min: 0,
max: 5
},
facilities: [String],
// Always store coordinates longitude, latitude order.
coords: {
type: [Number],
index: '2dsphere'
},
openingTimes: [openingTimeSchema],
reviews: [reviewSchema]
});
mongoose.model('Location', locationSchema);

当我请求GET localhost时,它应该返回Mongoshell测试查询中的JSON对象:3000 / api / locations / 594d96ab87e3602861443e1e
答案 0 :(得分:0)
您的findById()
功能可能失败。您是否尝试记录err
变量以查看是否发生了错误?
Loc
.findById (req.params.locationid)
.exec (function (err, location){
if(err) console.log("err", err)
sendJsonResponse (res, 200, location);
});