[英]mongoose doesn't return the output with findById
我正在通過獲取 MEAN 應用程序一起學習 nodejs 和 mongodb
我的系統規格是
Ubuntu 16.04(64 位)
節點 v 6.1.0
npm v 3.8.6
"mongodb": "^2.1.18",
"貓鼬": "^4.4.16",
到目前為止,我已經創建的模式,並通過使用終端添加MongoDB的集合中的條目db.locations.save()
與並得到生成的文檔_id db.locations.find()
db.locations.find().pretty() 在終端返回低於輸出
{
"_id" : ObjectId("57428745e89f5c55e1d057dc"),
// and many other path
}
現在,當我在瀏覽器中打開/api/locations/57428745e89f5c55e1d057dc時,它既不給出結果也不結束請求。 使用郵遞員進行測試時,永久顯示正在加載。
甚至嘗試使用錯誤的 ID 比它返回正確的錯誤
{"message":"Cast to ObjectId failed for value \\"57428745e89f5c55e1d057dca\\" at path \\"_id\\"","name":"CastError","kind":"ObjectId","value":"57428745e89f5c55e1d05 "路徑":"_id"}
並使用正確的 ID
console.log(mongoose.Types.ObjectId.isValid(req.params.locationid)); // return true
甚至嘗試過
findOne({"_id": mongoose.Types.ObjectId(req.params.locationid) })
但是沒有結果
可能是什么問題? 貓鼬中是否有任何錯誤或缺少任何內容。以下是我的基本文件以及所需代碼
require('./app_api/models/db');
var routesApi = require('./app_api/routes/index');
app.use('/api', routesApi);
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');
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);
var express = require('express');
var router = express.Router();
var ctrlLocations = require('../controllers/locations');
/* Locations pages */
router.get('/locations/:locationid', ctrlLocations.locationsReadOne);
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);
};
1.在 if 之前控制台你的 req.params
loc8r/app_api/controllers/locations.js
var mongoose = require('mongoose');
var Loc = mongoose.model('Location');
module.exports.locationsReadOne = function (req, res) {
控制台.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);
};
如果參數為空,或控制台不起作用,請檢查您的路由路徑
或
或
從貓鼬文檔中獲取解決方案
重要! 如果您使用 mongoose.createConnection() 打開了一個單獨的連接,但嘗試通過 mongoose.model('ModelName') 訪問模型,它將無法按預期工作,因為它沒有連接到活動的數據庫連接。 在這種情況下,通過您創建的連接訪問您的模型:
所以改變我創建連接的方式
//var mongoDB = mongoose.createConnection(mongoURI);
mongoose.connect(mongoURI);
還需要注釋所有其他使用mongoDB變量的函數/表達式
替代方法:(如果您不想在db.js中更改mongoDB )
在控制器/locations.js
更改var Loc = mongoose.model('Location');
用下面的線
var conn = mongoose.createConnection('mongodb://localhost/loc8r');
var Loc = mongoose.model('Location');
我遇到了類似的問題,所以我更新了我的模型文件。 例如
const workoutsSchema = new Schema({
_id: mongoose.ObjectId,
email_add: String,
workout_date: String,
workout_duration: String
});
在控制器中:-
router.route("/workouts/:id").get(function(req, res) {
console.log("Fetch Workouts of="+req.params.id);
var id = new mongoose.Types.ObjectId(req.params.id);
Workouts.findById(id, function(err, workout) {
if (err)
res.send(err)
res.json(workout);
});
});
嘗試像這樣重寫位置控制器
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"})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.