mongoose不会使用findById

时间:2016-05-23 06:27:39

标签: node.js mongodb mongoose

我正在使用getting MEAN application

学习nodejs和mongodb

我的系统规格是

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

“mongodb”:“^ 2.1.18”,
“mongoose”:“^ 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 \””, “名称”: “CastError”, “种类”: “的ObjectId”, “值”: “57428745e89f5c55e1d057dca”, “路径”: “_ ID”}

并且ID正确

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

甚至尝试过

findOne({"_id": mongoose.Types.ObjectId(req.params.locationid) })

但没有结果

可能是什么问题? mongoose中是否有任何错误或任何遗漏.Below是我的基本文件,包含所需的代码

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

5 个答案:

答案 0 :(得分:1)

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

如果params为空,或者控制台无法正常工作,请检查您的路径

  1. 控制sendJsonResponse内部的东西,也许你的功能不起作用。因为如果永久显示加载,则表示您不发送回复。
    1. 尝试将mongodb更新到最新版本,也许mongob工作不正确mongodb 2.1.18。它真的很老了。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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

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