2016-09-06 14 views
1

我一直在節點和mongo一段時間,但現在這個問題沒有得到解決現在問題: 這是我的代碼:顯示爲_id鑄造錯誤,但ID從未使用節點js

router.get('/getLocBJ', function(req, res) { 
    mongoose.model('Locations').find({ 
    }, function(err, locations) { 
     res.format({ 
      json: function() { 
       res.json(locations); 
      } 
     }); 
    }).limit(500); 
}); 

每當我把這個API 我所期望的:它顯示我此錯誤:應該從收集 發生了什麼事返回500行

GET Error: There was a problem retrieving: CastError: Cast to ObjectId failed for value "getLocBJ" at path "_id" 

我所做之前:我試圖返回一些特定的值如「_id,lat & lng」從那以後,它顯示了同樣的錯誤,即使從函數中刪除罪魁禍首代碼似乎沒有工作。 嘗試清除系統緩存但沒有成功。

編輯使用的模式:

var mongoose = require('mongoose'); 
var locationSchema = new mongoose.Schema({ 
    trackernumber: String, 
    cdate : String, 
    accountId : String,  
    time : String,  
    speed : String,  
    lat : String, 
    lng : String,  
    orientation:String, 
    createdDate:Date, 
    rowData:{}, 
    alarm_code : String, 
    distance : String, 
    alarm : {}, 
    locFlag : String  
}); 
mongoose.model('Locations', locationSchema); 

回答

1

所以,花了超過2天的這件事情後,幸運的是,我解決了這個問題。 這是發生在所有得到我最近在開發的API。

我如何解決這個,

這是一種奇怪的解決方案雖然不知道它是如何工作 (所以我也請看一看的代碼相同):

router.get('/:id/getLocBJ', function(req, res) { 
    mongoose.model('Locations').find({ 
    }, function(err, locations) { 
     res.format({ 
      json: function() { 
       res.json(locations); 
      } 
     }); 
    }).limit(500); 
}); 

我只是增加了一個得到 PARAM:在API調用「/ ID」:

router.get('/:id/getLocBJ', function(req, res) { 

和錯誤飛走了,我還沒有得到它的工作方式。

如果任何人都可以幫助詳細說明這將是非常有益的。

感謝

0

可以試試這個:

router.get('/getLocBJ', function(req, res) { 
    mongoose.model('Locations').find().limit(500).exec(function(err, locations) { 
    if(err) { 
     return res.status(500).send({msg: 'Error occurred'}); 
    } 
    return res.status(200).send(locations); 
    }); 
}); 

並導出使用module.exports你的模型,因爲你作爲mongoose.model('Locations')否則,你可能會遇到錯誤。

module.exports = mongoose.model('Locations', locationSchema); 

N.B:如果您手動添加_id值或當您使用的模型,然後先刪除該文件。 _id自動生成,所以你不需要手動添加或架構

+0

的_id字段自動生成的我還沒有手動和爲你建議我嘗試使用,但仍是同樣的結果代碼添加它。 – VishAl

+0

你能顯示你的模式嗎? –

+0

好吧,請檢查編輯 – VishAl