mongoose不返回带有findById的输出

mlmc2os5  于 11个月前  发布在  Go
关注(0)|答案(6)|浏览(144)

我正在使用getting MEAN application学习nodejs和mongodb。
我的系统规格是
Ubuntu 16.04(64 bit)
node v6.1.0
npm v3.8.6
“mongodb”:“^2.1.18”,
“mongoose”:“^4.4.16”,
到目前为止,我已经创建了schema,并通过终端使用db.locations.save()在mongodb集合中添加了一个条目,并使用db.locations.find()获得了生成的文档**_id**。
terminal中的db.locations.find().pretty()在输出下面返回

{
    "_id" : ObjectId("57428745e89f5c55e1d057dc"),
     // and many other path 
}

字符串
现在我在浏览器中打开**/API/locations/57428745 e89 f5 c55 e1 d 057 dc**,既没有给出结果,也没有结束请求。使用postman测试时,永久显示加载中。
即使尝试了错误的ID比它返回正确的错误
{“message”:“在路径"_id"”处的值\“57428745 e89 f5 c55 e1 d 057 dca\”转换为ObjectId失败,“name”:“CastError”,“kind”:“ObjectId”,“value”:“57428745 e89 f5 c55 e1 d 057 dca”,“path”:“_id”}
正确的ID

console.log(mongoose.Types.ObjectId.isValid(req.params.locationid));  // return true


甚至试图
findOne({"_id": mongoose.Types.ObjectId(req.params.locationid) })
但没有结果
可能是什么问题?有没有什么在mongoose错误或任何失踪。下面是我的基本文件所需的代码

loc8r/app.js

require('./app_api/models/db');
var routesApi = require('./app_api/routes/index');
app.use('/api', routesApi);

loc8r/app_api/models/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/models/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/router/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/locers/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);
};

zujrkrfu

zujrkrfu1#

我也遇到了类似的问题,所以我更新了我的模型文件。

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);
    });
});

mnowg1ta

mnowg1ta2#

**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) {

字符串

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);
};


如果params为空,或控制台不工作,则检查路由路径

  1. sendJsonResponse中的console,可能你的函数不工作。因为如果永久显示加载,这意味着你不发送响应。

1.试着把mongodb更新到最新版本,也许mongoose在mongodb 2.1.18上工作不正确。它真的是很旧的版本。

3phpmpom

3phpmpom3#

mongoose documentation获取解决方案

**重要!**如果您使用mongoose. modelConnection()打开了一个单独的连接,但试图通过mongoose.model('ModelName')访问模型,它将无法正常工作,因为它没有连接到活动的数据库连接。在这种情况下,通过您创建的连接访问您的模型:

所以改变我建立联系的方式

//var mongoDB = mongoose.createConnection(mongoURI);
mongoose.connect(mongoURI);

字符串
还需要注解所有其他使用 mongoDB 变量的函数/表达式

替代方法:(如果不想在db.js中更改 mongoDB

controllers/locations.js
var Loc = mongoose.model('Location');改为下面的行

var conn = mongoose.createConnection('mongodb://localhost/loc8r');
var Loc = mongoose.model('Location');

nzk0hqpo

nzk0hqpo4#

尝试像这样重写位置控制器

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"})
}

字符串

bakd9h0s

bakd9h0s5#

嘿,试着把你的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"})
}

字符串

n6lpvg4x

n6lpvg4x6#

findById()方法中将req.params.locationid更改为req.query.locationid

相关问题