MongoDB的Java堆栈新手,需要帮助来了解此错误的原因。
我创建了我的模型:
const
Mongoose = require('mongoose');
Schema = Mongoose.Schema,
Model = Mongoose.model;
module.exports = Model('Project',
new Schema({
icon : String,
name : String,
state : String,
number : String
})
);
这是我的MongoDB文档:
[![MongoDB Document][1]][1]
调用API时,我试图接收集合中的所有文档,因此,根据Mongoose文档,我正在使用find()方法。
这是我的API实现:
const Project = require('../../models/project');
router.get('/projects/:page?/:limit?',
function(req, res, next){
const page = Math.max(req.params.page || 1, 1) - 1;
const limit = Math.max(req.params.limit || 20, 20);
//Verified : I am hitting the API
console.log("Reached API /projects");
Project.find()
.populate('icon')
.populate('name')
.populate('state')
.populate('number')
.limit(limit).skip(page * limit).exec(
function(err, project)
{
if (err) { return next(err); }
res.send(project);
}
); //End of exec()
}//End of unction
);
我成功使用fetch()进行了API调用,但是我收到了所有String值的“ Cast to ObjectId failed error”。
我相信我的Mongo DB文档中确实存在一些可能非常简单的东西。请帮助我理解并解决此问题。
**编辑---
**
谢谢
答案 0 :(得分:0)
填充是使用其他集合中的文档自动替换文档中指定路径的过程。因此,您的Id转换无效,因为字符串,您需要具有ObjectId,在此之前需要进行一些更改,让我们进行调试:
const alldata = await Project.find()
console.log(alldata) // ?
这是否返回了某些内容,我在这里使用async await
,如果它返回了数据,那么问题在于您的填充,因为您的ID大小写无效,因为您保存在架构string
中,并且在这里重新引用填充,使用填充的示例:
module.exports = Model('Project',
new Schema({
icon : [{ type: Schema.ObjectId, ref: 'your icon document' }],
name : [{ type: Schema.ObjectId, ref: 'you name document' }],
state : [{ type: Schema.ObjectId, ref: 'state document' }],
number : [{ type: Schema.ObjectId, ref: 'number document' }]
})
);
但是在我看来,您不需要使用填充对象,因为您拥有简单的数据,名称,数字...,因此与上面的示例配合使用应该很好