Javascript 显示_id的强制转换错误,但从未使用id节点js
我已经在node和mongo上工作了一段时间,但是这个问题现在还没有解决,接下来是问题: 这是我的密码:Javascript 显示_id的强制转换错误,但从未使用id节点js,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我已经在node和mongo上工作了一段时间,但是这个问题现在还没有解决,接下来是问题: 这是我的密码: router.get('/getLocBJ', function(req, res) { mongoose.model('Locations').find({ }, function(err, locations) { res.format({ json: function() { res.json(lo
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);
你可以试试这个:
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);
注意:如果您手动或在使用模型创建时添加了\u id
值,请先删除该文档\u id
自动生成,因此您不需要手动或在模式中添加因此,在花了两天多的时间完成这件事之后,幸运的是,我解决了这个问题。
这发生在我最近开发的所有getapi中
我是如何解决这个问题的
这是一种奇怪的解决方案,尽管我不知道它是如何工作的
(因此,我所做的,请看一下相同的代码):
我刚刚在API调用中添加了一个getparam'/:id':
router.get('/:id/getLocBJ', function(req, res) {
错误飞走了,我仍然不知道它是怎么工作的
如果有人能帮助详细说明这一点,那将非常有帮助
谢谢id字段是自动生成的,我没有手动添加它&对于您建议的代码,我尝试使用它,但结果仍然相同。此错误通常发生在findById
方法中,而不是find
方法中,因此应该在我的查询中使用。只需导出
模型即可
router.get('/:id/getLocBJ', function(req, res) {