Получение ошибки “Приведение к ObjectId” с Heroku, но не с LocalHost?

#node.js #mongodb #heroku #mongoose #mongodb-query

#node.js #mongodb #heroku #mongoose #mongodb-запрос

Вопрос:

Моя страница «уроки / новые» нормально загружается на моем localhost, но выдает ошибку с heroku. Страница загрузится, но сразу после этого в heroku произойдет сбой. Я добавил console.log(foundClass) для getClassesById, и найденный класс был отображен правильно. Кто-нибудь, пожалуйста, может указать мне правильное направление?

class.js строки 27-33

 module.exports.getClassesById = function(id, callback){
    Class.findById(id)
    .populate(
        {path: 'lessons',
        model: 'Lesson', $ne: null}
    ).exec(callback)
}
  

classes.js

 router.get('/:id/lessons/new', function(req, res, next) {
    Class.getClassesById([req.params.id], function(err, foundClass){
        if (err){
            console.log(err)
            throw err
        } else {
            if (req.user amp;amp; req.user.email == foundClass.instructor_email){
                res.render('lessons/new', {class_id: req.params.id})
            } else {
                res.redirect('/');
            }
        }
    }) 
});
  

журналы heroku

 2016-10-24T17:31:08.413872 00:00 app[web.1]: [0mGET /classes/580e0e820a1e5d00118e6159/lessons/new [36m304 [0m30.674 ms - -[0m
2016-10-24T17:31:08.486402 00:00 app[web.1]: [0mGET /stylesheets/bootstrap.min.css [36m304 [0m2.559 ms - -[0m
2016-10-24T17:31:08.486823 00:00 app[web.1]: [0mGET /stylesheets/style.css [36m304 [0m2.326 ms - -[0m
2016-10-24T17:31:08.487513 00:00 app[web.1]: [0mGET /stylesheets/ie10-viewport-bug-workaround.css [36m304 [0m2.315 ms - -[0m
2016-10-24T17:31:08.489252 00:00 app[web.1]: [0mGET /stylesheets/jumbotron.css [36m304 [0m3.708 ms - -[0m
2016-10-24T17:31:08.529026 00:00 app[web.1]: [0mGET /js/bootstrap.min.js [36m304 [0m2.226 ms - -[0m
2016-10-24T17:31:08.530994 00:00 app[web.1]: [0mGET /js/ie10-viewport-bug-workaround.js [36m304 [0m0.699 ms - -[0m
2016-10-24T17:31:09.037191 00:00 app[web.1]: { CastError: Cast to ObjectId failed for value "[ 'favicon.ico' ]" at path "_id"
2016-10-24T17:31:09.037205 00:00 app[web.1]:     at MongooseError.CastError (/app/node_modules/mongoose/lib/error/cast.js:26:11)
2016-10-24T17:31:09.037206 00:00 app[web.1]:     at ObjectId.cast (/app/node_modules/mongoose/lib/schema/objectid.js:147:13)
2016-10-24T17:31:09.037207 00:00 app[web.1]:     at ObjectId.castForQuery (/app/node_modules/mongoose/lib/schema/objectid.js:187:15)
2016-10-24T17:31:09.037208 00:00 app[web.1]:     at cast (/app/node_modules/mongoose/lib/cast.js:225:32)
2016-10-24T17:31:09.037209 00:00 app[web.1]:     at Query.cast (/app/node_modules/mongoose/lib/query.js:2737:10)
2016-10-24T17:31:09.037209 00:00 app[web.1]:     at Query.findOne (/app/node_modules/mongoose/lib/query.js:1350:10)
2016-10-24T17:31:09.037210 00:00 app[web.1]:     at /app/node_modules/mongoose/lib/query.js:2296:21
2016-10-24T17:31:09.037210 00:00 app[web.1]:     at new Promise.ES6 (/app/node_modules/mongoose/lib/promise.js:45:3)
2016-10-24T17:31:09.037211 00:00 app[web.1]:     at Query.exec (/app/node_modules/mongoose/lib/query.js:2290:17)
2016-10-24T17:31:09.037211 00:00 app[web.1]:     at Function.module.exports.getClassesById (/app/models/class.js:32:4)
2016-10-24T17:31:09.037212 00:00 app[web.1]:     at /app/routes/classes.js:105:8
2016-10-24T17:31:09.037213 00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:82:5)
2016-10-24T17:31:09.037213 00:00 app[web.1]:     at next (/app/node_modules/express/lib/router/route.js:110:13)
2016-10-24T17:31:09.037214 00:00 app[web.1]:     at Route.dispatch (/app/node_modules/express/lib/router/route.js:91:3)
2016-10-24T17:31:09.037214 00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:82:5)
2016-10-24T17:31:09.037214 00:00 app[web.1]:     at /app/node_modules/express/lib/router/index.js:267:22
2016-10-24T17:31:09.037215 00:00 app[web.1]:     at param (/app/node_modules/express/lib/router/index.js:340:14)
2016-10-24T17:31:09.037215 00:00 app[web.1]:     at param (/app/node_modules/express/lib/router/index.js:356:14)
2016-10-24T17:31:09.037216 00:00 app[web.1]:     at Function.proto.process_params (/app/node_modules/express/lib/router/index.js:400:3)
2016-10-24T17:31:09.037216 00:00 app[web.1]:     at next (/app/node_modules/express/lib/router/index.js:261:10)
2016-10-24T17:31:09.037216 00:00 app[web.1]:     at Function.proto.handle (/app/node_modules/express/lib/router/index.js:166:3)
2016-10-24T17:31:09.037217 00:00 app[web.1]:     at router (/app/node_modules/express/lib/router/index.js:35:12)
2016-10-24T17:31:09.037217 00:00 app[web.1]:   message: 'Cast to ObjectId failed for value "[ 'favicon.ico' ]" at path "_id"',
2016-10-24T17:31:09.037218 00:00 app[web.1]:   name: 'CastError',
2016-10-24T17:31:09.037218 00:00 app[web.1]:   kind: 'ObjectId',
2016-10-24T17:31:09.037218 00:00 app[web.1]:   value: [ 'favicon.ico' ],
2016-10-24T17:31:09.037219 00:00 app[web.1]:   path: '_id',
2016-10-24T17:31:09.037219 00:00 app[web.1]:   reason: undefined }
2016-10-24T17:31:09.038731 00:00 app[web.1]: 
2016-10-24T17:31:09.038733 00:00 app[web.1]: events.js:160
2016-10-24T17:31:09.038734 00:00 app[web.1]:       throw er; // Unhandled 'error' event
2016-10-24T17:31:09.038734 00:00 app[web.1]:       ^
2016-10-24T17:31:09.038768 00:00 app[web.1]: CastError: Cast to ObjectId failed for value "[ 'favicon.ico' ]" at path "_id"
2016-10-24T17:31:09.038769 00:00 app[web.1]:     at MongooseError.CastError (/app/node_modules/mongoose/lib/error/cast.js:26:11)
2016-10-24T17:31:09.038770 00:00 app[web.1]:     at ObjectId.cast (/app/node_modules/mongoose/lib/schema/objectid.js:147:13)
2016-10-24T17:31:09.038771 00:00 app[web.1]:     at ObjectId.castForQuery (/app/node_modules/mongoose/lib/schema/objectid.js:187:15)
2016-10-24T17:31:09.038771 00:00 app[web.1]:     at cast (/app/node_modules/mongoose/lib/cast.js:225:32)
2016-10-24T17:31:09.038772 00:00 app[web.1]:     at Query.cast (/app/node_modules/mongoose/lib/query.js:2737:10)
2016-10-24T17:31:09.038773 00:00 app[web.1]:     at Query.findOne (/app/node_modules/mongoose/lib/query.js:1350:10)
2016-10-24T17:31:09.038773 00:00 app[web.1]:     at /app/node_modules/mongoose/lib/query.js:2296:21
2016-10-24T17:31:09.038774 00:00 app[web.1]:     at new Promise.ES6 (/app/node_modules/mongoose/lib/promise.js:45:3)
2016-10-24T17:31:09.038774 00:00 app[web.1]:     at Query.exec (/app/node_modules/mongoose/lib/query.js:2290:17)
2016-10-24T17:31:09.038775 00:00 app[web.1]:     at Function.module.exports.getClassesById (/app/models/class.js:32:4)
2016-10-24T17:31:09.038776 00:00 app[web.1]:     at /app/routes/classes.js:105:8
2016-10-24T17:31:09.038776 00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:82:5)
2016-10-24T17:31:09.038777 00:00 app[web.1]:     at next (/app/node_modules/express/lib/router/route.js:110:13)
2016-10-24T17:31:09.038778 00:00 app[web.1]:     at Route.dispatch (/app/node_modules/express/lib/router/route.js:91:3)
2016-10-24T17:31:09.038778 00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:82:5)
2016-10-24T17:31:09.038779 00:00 app[web.1]:     at /app/node_modules/express/lib/router/index.js:267:22
2016-10-24T17:31:09.038779 00:00 app[web.1]:     at param (/app/node_modules/express/lib/router/index.js:340:14)
2016-10-24T17:31:09.038780 00:00 app[web.1]:     at param (/app/node_modules/express/lib/router/index.js:356:14)
2016-10-24T17:31:09.038780 00:00 app[web.1]:     at Function.proto.process_params (/app/node_modules/express/lib/router/index.js:400:3)
2016-10-24T17:31:09.038781 00:00 app[web.1]:     at next (/app/node_modules/express/lib/router/index.js:261:10)
2016-10-24T17:31:09.038781 00:00 app[web.1]:     at Function.proto.handle (/app/node_modules/express/lib/router/index.js:166:3)
2016-10-24T17:31:09.038782 00:00 app[web.1]:     at router (/app/node_modules/express/lib/router/index.js:35:12)
2016-10-24T17:31:09.051877 00:00 app[web.1]: 
2016-10-24T17:31:09.059912 00:00 app[web.1]: npm ERR! Linux 3.13.0-100-generic
2016-10-24T17:31:09.060095 00:00 app[web.1]: npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
2016-10-24T17:31:09.060223 00:00 app[web.1]: npm ERR! node v6.6.0
2016-10-24T17:31:09.060321 00:00 app[web.1]: npm ERR! npm  v3.10.3
2016-10-24T17:31:09.060423 00:00 app[web.1]: npm ERR! code ELIFECYCLE
2016-10-24T17:31:09.060516 00:00 app[web.1]: npm ERR! eTeacher@0.0.1 start: `node ./bin/www`
2016-10-24T17:31:09.060581 00:00 app[web.1]: npm ERR! Exit status 1
2016-10-24T17:31:09.060664 00:00 app[web.1]: npm ERR! 
2016-10-24T17:31:09.060738 00:00 app[web.1]: npm ERR! Failed at the eTeacher@0.0.1 start script 'node ./bin/www'.
2016-10-24T17:31:09.060808 00:00 app[web.1]: npm ERR! Make sure you have the latest version of node.js and npm installed.
2016-10-24T17:31:09.060873 00:00 app[web.1]: npm ERR! If you do, this is most likely a problem with the eTeacher package,
2016-10-24T17:31:09.060940 00:00 app[web.1]: npm ERR! not with npm itself.
2016-10-24T17:31:09.061016 00:00 app[web.1]: npm ERR! Tell the author that this fails on your system:
2016-10-24T17:31:09.061085 00:00 app[web.1]: npm ERR!     node ./bin/www
2016-10-24T17:31:09.061153 00:00 app[web.1]: npm ERR! You can get information on how to open an issue for this project with:
2016-10-24T17:31:09.061212 00:00 app[web.1]: npm ERR!     npm bugs eTeacher
2016-10-24T17:31:09.061280 00:00 app[web.1]: npm ERR! Or if that isn't available, you can get their info via:
2016-10-24T17:31:09.061347 00:00 app[web.1]: npm ERR!     npm owner ls eTeacher
2016-10-24T17:31:09.061415 00:00 app[web.1]: npm ERR! There is likely additional logging output above.
2016-10-24T17:31:09.065020 00:00 app[web.1]: 
2016-10-24T17:31:09.065328 00:00 app[web.1]: npm ERR! Please include the following file with any support request:
2016-10-24T17:31:09.065465 00:00 app[web.1]: npm ERR!     /app/npm-debug.log
  

Схема класса

 var classSchema = new Schema({
    title: { type: String, required: true },
    description: { type: String, required: true },
    instructor: { type: String, required: true },
    instructor_email: { type: String, required: true },
    //Lessons for the class
    lessons: [
        { type: mongoose.Schema.Types.ObjectId, ref: 'Lesson' }
    ],
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
    created : { type : Date, default : Date.now }
});
  

‘classes / show’ — это страница, с которой она поступает
classes.js 104-114

 router.get('/:id', function(req, res, next) {
    Class.getClassesById([req.params.id], function(err, foundClass){
        if (err){
            console.log(err)
            throw err
        } else {
            console.log('Found class.')
            res.render('classes/show', {"class": foundClass})
        }
    });
});
  

Комментарии:

1. favicon.ico действительный идентификатор?

Ответ №1:

Это выдает эту ошибку, потому что идентификатор Mongo должен иметь определенный формат. В журнале ошибок указано, что в качестве параметра был получен «favicon.ico», что нарушает формат идентификатора Mongo.

Вы всегда должны проверять данные перед выполнением операций с базой данных.

Есть пакет для проверки и очистки строк: https://www.npmjs.com/package/validator

Вы можете проверить, находится ли параметр в правильном формате с помощью:

 var validator = require('validator');
  

тогда в вашем маршруте:

 if (!validator.isMongoId(req.params.id)) {
    // Param is not mongoId, throw error
}