【问题标题】:猫鼬不使用 findById 返回输出
【发布时间】:2016-09-19 21:59:45
【问题描述】:

我正在和getting MEAN application一起学习nodejs和mongodb

我的系统规格是

ubuntu 16.04(64 位)
节点 v 6.1.0
npm v 3.8.6

"mongodb": "^2.1.18",
"猫鼬": "^4.4.16",

到目前为止,我已经创建了架构并通过终端使用db.locations.save() 在 mongodb 集合中添加了一个条目,并使用db.locations.find() 获取生成的文档 _id

终端中的 db.locations.find().pretty() 在输出下方返回

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

现在当我在浏览器中打开 /api/locations/57428745e89f5c55e1d057dc 时,它既没有给出结果也没有结束请求。使用邮递员进行测试时,永久显示正在加载。

即使尝试使用错误的 ID 也不会返回正确的错误

{"message":"转换为 ObjectId 的值失败 \"57428745e89f5c55e1d057dca\" 在路径 \"_id\"","name":"CastError","kind":"ObjectId","value":"57428745e89f5c55e1d057dca","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/controllers/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);
};

【问题讨论】:

  • 对不起,但这并不能解决我的问题。已经搜索过 google 和 mongoose github 问题。
  • 你试过其他答案了吗?
  • 是的。我创建了新文档并尝试过。没有帮助
  • 你确定locationsReadOne 已经被联系到了吗?您是否在应用中使用了某种可能导致请求挂起的中间件?

标签: node.js mongodb mongoose


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!
【解决方案2】:

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

如果参数为空,或者控制台不起作用,请检查您的路由路径

  1. 在 sendJsonResponse 中进行控制台操作,可能您的功能不起作用。因为如果永久显示加载,则意味着您不发送响应。

  1. 尝试将 mongodb 更新到最新版本,可能 mongoose 在 mongodb 2.1.18 上工作不正确。真的是很老的版本了。

【讨论】:

  • console.log(req.params) 输出 { locationid: '57428745e89f5c55e1d057dc' }
  • 也将 mongodb 升级到 3.2.6 但仍然没有区别
  • 如果我更改 locationid 的最后一个字符,它不会抛出任何错误
  • 尝试另一个查询到另一个集合。可能是月鹅连接的问题......或者尝试使用另一个文件查找。
  • 抱歉,我的 ubuntu 16.04 上无法安装最新的 mongodb / 也尝试使用其他集合但同样的问题。看我的下一个问题Here
【解决方案3】:

mongoose documentation获取解决方案

重要!如果您使用 mongoose.createConnection() 但尝试通过 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');

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

    • 您使用不同的方法与 res.status ,一次 .send 和两次 .json ,为什么会这样?
    • 我刚刚修改了人的代码给出了这个问题。我觉得没必要
    【解决方案5】:

    嘿,尝试将您的 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"})
    }
    

    【讨论】:

    • 我需要在 controllers/locations 中包含 models/locations 文件还是当前方法可以?
    • 您是否尝试过使用 find 或 findOne 等其他方法?它给你同样的错误吗?
    • 是的。我尝试了findfindOne .. 都要求保持挂起
    • 你控制结果了吗?你得到了什么?
    • nothing.request 结束于GET /api/locations/5742b0e3b7d7c67dc946d9f3 - - ms - -
    猜你喜欢
    • 2019-02-08
    • 1970-01-01
    • 2018-02-05
    • 2023-03-20
    • 1970-01-01
    • 2019-09-10
    • 2019-02-15
    相关资源
    最近更新 更多