【发布时间】:2018-07-10 00:26:21
【问题描述】:
我正在尝试通过 id 从 mongo 检索数据,但当我添加外部链接(如样式文件或脚本文件)时,它运行良好,但我收到此错误消息。
消息:“在路径“_id”处的值“script.js”转换为 ObjectId 失败 对于模型“博客”,名称:'CastError',字符串值:'“script.js”', 种类:'ObjectId',值:'script.js',路径:'_id',原因: 未定义,型号:
const express = require('express'),
ejs = require('ejs'),
bodyParser = require('body-parser'),
Blog = require('./models/blog');
const app = express(),
port = 5000;
// mongoose.connect('mongodb://localhost/blog_v1', {useMongoClient: true});
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', (req, res) => {
Blog.find({},(error, blogs) => {
if(error) {
console.log(`something went wrong ${error}`);
} else {
// console.log(blogs);
res.render('home', {blogs: blogs});
}
});
});
// findById or find({'_id': 'id'})
app.get('/posts/:id', (req, res) => {
Blog.findById(req.params.id, (error, foundPost) => {
if(error) {
console.log(error);
console.log(req.params.id);
} else {
res.render('posts', {foundPost: foundPost});
console.log(req.params.id);
}
});
});
app.listen(process.env.PORT || 5000, () => {
console.log(`Server is up on port ${port}`);
});
【问题讨论】:
标签: javascript node.js mongodb