mongoose不会用findById返回输出
我正在学习nodejs和mongodb以获得MEAN应用程序
我的系统规格是
Ubuntu的16.04(64位)
节点v 6.1.0
npm v 3.8.6
“mongodb”:“^ 2.1.18”,
“mongoose”:“^ 4.4.16”,
到目前为止,我已经创build了模式,并通过terminal使用db.locations.save()
在mongodb集合中添加一个条目,并使用db.locations.save()
获取生成的文档_id 。
db.locations.find()。pretty()在terminal返回输出
{ "_id" : ObjectId("57428745e89f5c55e1d057dc"), // and many other path }
现在当我在浏览器中打开/ api / locations / 57428745e89f5c55e1d057dc时,它既不给出结果也不结束请求。 永久显示加载..当与邮递员testing。
甚至尝试与错误的ID比它返回适当的错误
{“message”:“在path\”_ id \“”,“name”:“CastError”,“kind”:“ObjectId”,“value”:“57428745e89f5c55e1d057dca”上投射到ObjectId的值“57428745e89f5c55e1d057dca”失败“path”: “_ ID”}
并用正确的ID
console.log(mongoose.Types.ObjectId.isValid(req.params.locationid)); // return true
甚至尝试过
findOne({"_id": mongoose.Types.ObjectId(req.params.locationid) })
但没有结果
可能是什么问题? 有没有mongoose或缺less任何错误。以下是我的基本文件与所需的代码
loc8r / app.js
require('./app_api/models/db'); var routesApi = require('./app_api/routes/index'); app.use('/api', routesApi);
loc8r / app_api /模型/ db.js
var mongoose = require( 'mongoose' ); var mongoURI = 'mongodb://localhost/loc8r'; var mongoDB = mongoose.createConnection(mongoURI); mongoDB.on('connected', function (){ console.log('mongoose connected to ' + mongoURI); }); require('./locations');
loc8r / app_api /模型/ locations.js
var mongoose = require( 'mongoose' ); var openingTimeSchema = new mongoose.Schema({ days: {type: String, required: true}, opening: String, closing: String, closed: {type: Boolean, required: true} }); var reviewSchema = new mongoose.Schema({ author: String, rating: {type: Number, required: true, min: 0, max: 5}, reviewText: String, createdOn: {type: Date, "default": Date.now} }); var locationSchema = new mongoose.Schema({ name: {type: String, required: true}, address: String, rating: {type: Number, "default": 0, min: 0, max: 5}, facilities: [String], coords: {type: [Number], index: '2dspehere'}, openingTime: [openingTimeSchema], reviews: [reviewSchema] }); mongoose.model('Location', locationSchema);
loc8r / app_api /路由器/ index.js
var express = require('express'); var router = express.Router(); var ctrlLocations = require('../controllers/locations'); /* Locations pages */ router.get('/locations/:locationid', ctrlLocations.locationsReadOne);
loc8r / app_api /控制器/ locations.js
var mongoose = require('mongoose'); var Loc = mongoose.model('Location'); module.exports.locationsReadOne = function (req, res) { if(req.params && req.params.locationid) { Loc .findById(req.params.locationid) .exec(function(err, location) { if(err) { sendJsonResponse(res, 404, err); return; } if (!location) { sendJsonResponse(res, 404, {"message": "locationid not found"}); return; } sendJsonResponse(res, 200, location); }); } else { sendJsonResponse(res, 200, {"message": "no location id in request"}); } } var sendJsonResponse = function(res, status, content) { res.status(status); res.json(content); };
从mongoose文档获得解决scheme
重要! 如果您使用mongoose.createConnection()打开单独的连接,但是尝试通过mongoose.model('ModelName')访问模型,它将无法按预期工作,因为它没有连接到活动数据库连接。 在这种情况下,通过您创build的连接访问您的模型:
所以改变我创build连接的方式
//var mongoDB = mongoose.createConnection(mongoURI); mongoose.connect(mongoURI);
还需要注释所有其他使用mongoDBvariables的函数/expression式
替代方法:(如果你不想在db.js中更改mongoDB )
在控制器/ locations.js
更改var Loc = mongoose.model('Location');
与下面的线
var conn = mongoose.createConnection('mongodb://localhost/loc8r'); var Loc = mongoose.model('Location');
尝试像这样重写位置控制器
var mongoose = require('mongoose'), Location = mongoose.model('Location'); exports.locationsReadOne = function (req, res) { if (req.params && req.params.locationid) Location.findById(req.params.locationid, function (err, location) { if (err) return res.status(500).send(err); if (location) return res.status(200).json(location); return res.status(404).json({"message": "locationid not found"}) }) else return res.status(200).json({"message": "no location id in request"}) }
嘿尝试通过将您的ID转换为对象ID
var mongoose = require('mongoose'), Location = mongoose.model('Location'); exports.locationsReadOne = function (req, res) { if (req.params && req.params.locationid) Location.findById(mongoose.Types.ObjectId(req.params.locationid), function (err, location) { if (err) return res.status(500).send(err); if (location) return res.status(200).json(location); return res.status(404).json({"message": "locationid not found"}) }) else return res.status(200).json({"message": "no location id in request"}) }
1.如果你以前安慰你的req.params
loc8r / app_api /控制器/ locations.js
var mongoose = require('mongoose'); var Loc = mongoose.model('Location'); module.exports.locationsReadOne = function (req, res) {
执行console.log(req.params)
if(req.params && req.params.locationid) { Loc .findById(req.params.locationid) .exec(function(err, location) { if(err) { sendJsonResponse(res, 404, err); return; } if (!location) { sendJsonResponse(res, 404, {"message": "locationid not found"}); return; } sendJsonResponse(res, 200, location); }); } else { sendJsonResponse(res, 200, {"message": "no location id in request"}); } } var sendJsonResponse = function(res, status, content) { res.status(status); res.json(content); };
如果参数为空,或者控制台不工作,请检查您的pathpath
要么
- 控制台里面的东西sendJsonResponse,也许你的function不工作。 因为如果永久显示加载,这意味着你不发送回应。
要么
- 尝试更新mongodb到最新版本,也许mongoose工作与mongodb 2.1.18不正确。 它真的是非常旧的版本。