我一直在进行开发人员训练营,其中一项要求是将Goorm及其工作区容器用作开发人员环境。
直到几天前,一切都运行得非常顺利,直到我尝试连接到mongodb服务器(和以前一样)并且无法接通。我对代码进行了两次检查,确保服务器使用mongod命令在后台运行,并尝试将端口重置为无效。
下面,我包括了我编写的代码(供参考)
var express = require("express"),
app = express(),
bodyParser = require ("body-parser"),
mongoose = require("mongoose")
mongoose.connect("mongodb://localhost:27017/yelp_camp",{
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true });
//SCHEMA SETUP
var campgroundSchema = new mongoose.Schema({
name: String,
image: String,
description: String
});
var Campground = mongoose.model("Campground", campgroundSchema);
Campground.create(
{name: "Briesmann Forest",
image: "https://image.shutterstock.com/image-photo/pond-lily-pads-spanaway-lake-260nw-1741738061.jpg",
description: "This is a huge forest, full of Vampires, Faeries and the occasional witch."
},
function(err, campground){
if (err){
console.log(err);
} else {
console.log("NEWLY CREATED CAMPGROUND: ")
console.log(campground);
}
});
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.get("/", function(req, res){
res.render("landing");
});
//INDEX - show all campgrounds
app.get("/campgrounds", function(req, res){
//Get all Campgrounds from DB
Campground.find({}, function(err, allCampgrounds){
if (err){
console.log(err);
} else {
res.render("index",{campgrounds:allCampgrounds});
}
});
});
//res.render("campgrounds",{campgrounds:campgrounds});
//});
app.post("/campgrounds", function(req, res){
//get data from form and add to campgrounds array
// redirect to campgrounds page
var name= req.body.name;
var image= req.body.image;
var newCampground= {name: name, image: image}
//create new campground and save to DB
Campground.create(newCampground, function(err, newlyCreated){
if(err){
console.log("Err")
} else {
//redirect to the campgrounds page
res.redirect("/campgrounds");
}
});
});
//New - Show form to create new campground
app.get("/campgrounds/new", function(req, res){
res.render("new.ejs");
});
//SHOW - shows more info about one campgrounds
app.get("/campgrounds/:id", function (req, res){
//find campground with provided id
Campground.findById,(req.params.id, function(err, foundCampground){
if (err){
console.log (err)
} else {
//render show template with that campground
res.render ("show.ejs"), {campground:foundCampground};
}
});
app.listen(process.env.PORT || 3000, process.env.IP, function(){
console.log("The Yelp Camp server has started!")
});
});