【发布时间】:2020-10-21 04:40:30
【问题描述】:
我正在尝试在节点中运行我的 .js 脚本,但是在数据库中添加一些新数据时,服务器未加载并给出此错误(CastError: Cast to string failed for value)。我没有收到错误,有人可以帮我吗?附上 cmd 的 SS 和代码![在此处输入图像描述][1]
Code is as follows:
var express=require("express");
var app= express();
var bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended:true}));
app.set("view engine","ejs");
var mongoose=require("mongoose");
mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology",true);
mongoose.connect("mongodb://localhost/yelp_camp");
var campgroundsschema= new mongoose.Schema({
name:String,
image:String
});
var Campground= mongoose.model("Campground",campgroundsschema);
//Campground.create(
// {
// name:"Granite Hill",
//image:"https://images.unsplash.com/photo-1487750404521-0bc4682c48c5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"
//},function(err,campgrounds){
//if(err){
// console.log(err);
//}
//else{
// console.log("We have created a new campground");
// console.log(campgrounds);
//}
//}
//)
app.get("/",function(req,res){
res.render("landing");
});
app.get("/campgrounds",function(req,res){
Campground.find({},function(err,allCampgrounds){
if(err){
console.log(err);
}
else{
res.render("campgrounds",{campgrounds:allCampgrounds});
}
});
});
app.post("/campgrounds",function(req,res){
var name=req.body.name;
var image=req.body.image;
var newCampground={name: name,image: image};
Campground.create(newCampground,function(err,newlyCreated){
if(err){
console.log(err);
}
else{
console.log("we have created a new campground here!!");
res.redirect("/campgrounds");
}
});
});
app.get("/campgrounds/new",function(req,res){
res.render("newcamp.ejs");
});
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log('Example app listening on port ' + port + '!');
});
Error ScreenShot: [1]: https://i.stack.imgur.com/9vNPz.png
(请打开此链接查看图片)
【问题讨论】:
标签: node.js mongodb express mongoose web-development-server