【发布时间】:2021-07-04 11:59:05
【问题描述】:
前言:我对使用 mongoose/express 比较陌生。
我正在尝试制作一个应用程序,其中一个名为“Space”的猫鼬模式中有一个名为“posts”的数组。数组的内容是 ObjectId 对另一个名为“Post”的 mongoose Schema 的引用。但是,每次我向应该发回我的空间和其中的帖子的路线发出 GET 请求时,我都会收到一个令人讨厌的错误。另外,我的帖子没有填充我的空间。
错误:CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model "Space"
这是我的路线:
获取
app.get('/spaces/:id', (req,res) => {
Space.findById(req.params.id).populate('posts').exec((err, space) => {
if(err){
console.log(err);
} else {
res.send(space);
}
});
});
发布
app.post('/spaces/:id/posts', (req,res) => {
Space.findById(req.params.id, (err, space) => {
if(err){
console.log(err);
res.redirect('/spaces/:id');
} else {
Post.create(req.body, (err, newPost) => {
if(err){
console.log(err);
} else {
newPost.save();
space.posts.push(newPost._id);
res.redirect('/spaces/:id');
}
});
}
});
});
这是我的架构:
发布架构:
const mongoose = require('mongoose');
让 postSchema = new mongoose.Schema({ 标题:字符串, 描述:字符串 });
module.exports = mongoose.model("Post", postSchema);
空间架构:
const mongoose = require('mongoose');
让 spaceSchema = new mongoose.Schema({ 标题:字符串, 描述:字符串, 帖子:[ { 类型:mongoose.Schema.Types.ObjectId, 参考:“发布” } ] });
module.exports = mongoose.model('Space', spaceSchema);
【问题讨论】:
-
在调用findById方法
console.log(mongoose.isValidObjectId(req.params.id))之前检查req.params.id是否是一个有效的ObjecId -
嗨!我刚试了一下,我得到了“真实”。
-
看起来
req.params.id未定义。做一个 console.log(req.params.id) -
我收到了 req.params.id 的字符串。好像已经定义好了。
标签: node.js mongodb mongoose schema