2017-06-23 60 views
0

我正在做一個freecodecamp後端認證API項目「URL縮短」。我有一個基本的快速應用程序,通過貓鼬連接到mongodb。我建立了一個模型。我在cloud9(c9)開發環境中運行所有這些。但只要我啓動應用程序,它會引發此錯誤並停止錯誤返回mongoose mongodb文件

events.js:141 
    throw er; // Unhandled 'error' event 
^

TypeError: Cannot read property 'originalUrl' of null 
at /home/ubuntu/workspace/FCCBackendProjects/urlShortener/server.js:71:29 
at Query.<anonymous> (/home/ubuntu/workspace/FCCBackendProjects/urlShortener/node_modules/mongoose/lib/model.js:3755:16) 
at /home/ubuntu/workspace/FCCBackendProjects/urlShortener/node_modules/mongoose/node_modules/kareem/index.js:277:21 
at /home/ubuntu/workspace/FCCBackendProjects/urlShortener/node_modules/mongoose/node_modules/kareem/index.js:131:16 
at doNTCallback0 (node.js:408:9) 
at process._tickCallback (node.js:337:13) 

它說原始URL是未定義的。但它的定義。可能是什麼問題呢?需要幫助。

我的文件:

server.js:

var express = require("express"); 
var app = express(); 
var path = require("path"); 
var mongoose = require("mongoose"); 
var urlPairModel = require("./models/urls"); 
var validator = require("validator"); 

var port = process.env.PORT; 

app.use(express.static(path.join(__dirname, 'public'))); 

//connect to the database 
var mlabUrl = process.env.MONGOLAB_URI; //get mlab url(credentials) from 
environment variables and url-shortner is dbname 
mongoose.Promise = global.Promise; 
mongoose.connect("mongodb://localhost:27017/urlShortener"); /*connect to 
mongodb(on mlab, no locally) with mongoose 
either on mlab cloud remote database or locally installed mongodb*/ 

var connection = mongoose.connection; 
connection.on('error', console.error.bind(console, 'connection error:')) 
connection.on('open', function(){ 
console.log("connected correctly to the database"); 
    console.log(process.env.PORT); 
}) 

app.get("/new/:id(*)", function(request, response){ 

    var originalUrl = request.params.id; //url user typed in 

    //check if it's a valid url 
    if(!validator.isURL(originalUrl)){ 
     response.send({error: "you can enter only valid urls"}) 
    } 
    //create a shortened url representation 
    var shortCode = Math.floor(Math.random()*10000); 
    //create new urlpair from url model 
    var urlInstance = new urlPairModel({ 
     originalUrl : originalUrl, 
     shortenedUrl : shortCode 
    }); 

    //save urlPair data instance in the database 
    urlInstance.save(function(err,data){ 
     if(err){ 
      console.log(err); 
      response.send("Error saving to the database"); 
     } 
     else{ 
      //return back to the user only the original url and shortened form 
      console.log(data); 
      var appUrl = 'https://bexis-url-shortener.herokuapp.com/'; 
      response.send({ 
      originalUrl : originalUrl, 
      shortenedUrl : appUrl + shortCode 
      }); 
     } 
    }) 
}); 

app.get("/:id", function(request, response){ 
    //get users shortcode 
    var shortCode = request.params.id; 
    //find document with this shortcode in the database collection urlpairmodel 
    urlPairModel.findOne({'shortenedUrl':shortCode}, function(err, docs){ 
     if(err){ 
      response.send("cannot find your shortUrl in database. Please add it" + 
     " as new url /new/your_url_here"); 
     } 
     else{ 
      console.log(docs); 
      //check if docs original url does not have http in it 
      var check = docs["originalUrl"].substring(0,4); 
      //add http if it does not have 
      if(check !== "http"){ 
       var urlToVisit = "http://" + docs.originalUrl; 
       response.redirect(urlToVisit); 
      } 
      //it has http, so: 
      //redirect user to appropriate url representation of the shortcode 
      response.redirect(docs.originalUrl); 
     } 
    }) 
}) 

app.listen(port, function(){ 
    console.log("app is listening on port"); 
}) 

urls.js:

var mongoose = require("mongoose"); 

var Schema = mongoose.Schema; 

//create our url schema 
var urlModelSchema = new Schema({ 
    originalUrl : {type: String}, 
    shortenedUrl : {type: String} 
}, 
{ 
    timestamps : true 
}); 


//create our url model --> mongoose will pluralize it 
var urlModels = mongoose.model("urlModel", urlModelSchema); 

module.exports = urlModels; 
+1

對於第70行的文檔,「console.log」會打印出什麼內容? –

+0

它打印這樣的: '{ _id:594d356a1eb7cc13b7691828, updatedAt:星期五2017年6月23日15時36分10秒GMT + 0000(UTC), createdAt:星期五2017年6月23日15時36分10秒GMT + 0000(UTC) , originalUrl: 'https://www.google.com', shortenedUrl: '7529', __v:0 }' – bexis

+0

可以打印'的console.log(docs.originalUrl)'並檢查錯誤ocurs 。 –

回答

0

解決這一問題被檢查,如果該文檔是不是空的訪問值

該代碼

app.get("/:id", function(request, response) { 
    //get users shortcode 
    var shortCode = request.params.id; 
    //find document with this shortcode in the database collection urlpairmodel 
    urlPairModel.findOne({ 
    'shortenedUrl': shortCode 
    }, function(err, docs) { 
    if (err) { 
     response.send("cannot find your shortUrl in database. Please add it" + 
     " as new url /new/your_url_here"); 
    } else { 
     // Soltuion part 
     if (docs) { // Checking if docs are available before accessing 
     //check if docs original url does not have http in it 
     var check = docs["originalUrl"].substring(0, 4); 
     //add http if it does not have 
     if (check !== "http") { 
      var urlToVisit = "http://" + docs.originalUrl; 
      response.redirect(urlToVisit); 
     } 
     //it has http, so: 
     //redirect user to appropriate url representation of the shortcode 
     response.redirect(docs.originalUrl); 
     } 
    } 
    }) 
}) 
+0

太棒了!被困在這一段時間。我正在考慮nodejs異步回調函數,自動傳回一個有它的錯誤,然後是文檔,如果有文檔的話。 **我想你明確地必須檢查文檔是否仍然可用。** NOTED。希望這可以幫助別人。無論如何stackoverflow岩石。再次感謝@Prabodh – bexis

+0

它類似於mysql的東西,如果你沒有數據。這是一個空白的迴應。同樣如果沒有找到數據,它仍然會成功。在查詢成功觸發時,只有匹配的數據不存在。 –