refer to: https://www.udemy.com/course/the-web-developer-bootcamp
image source: https://source.unsplash.com/
models/campground.js
const mongoose = require(‘mongoose‘); const Schema = mongoose.Schema; const CampgroundSchema = new Schema({ title: String, image: String, Price: Number, description: String, location: String }); module.exports = mongoose.model(‘Campground‘, CampgroundSchema);
seeds/index.js
const mongoose = require(‘mongoose‘); const cities = require(‘./cities‘); const { places, descriptors } = require(‘./seedHelpers‘); const Campground = require(‘../models/campground‘); // ".." to get outside the seeds folder mongoose.connect(‘mongodb://localhost:27017/yelp-camp‘, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true }); const db = mongoose.connection; db.on(‘error‘, console.error.bind(console, ‘connection error:‘)); db.once(‘open‘, function () { console.log("Database connected"); }); // array[Math.floor(Math.random() * array.length)], 产生0~数组长度-1的随机数 const sample = array => array[Math.floor(Math.random() * array.length)]; const seedDB = async () => { await Campground.deleteMany({});//删除之前的记录 for (let i = 0; i < 50; i++) { const random1000 = Math.floor(Math.random() * 1000);//包含1000个城市, 0-999的随机数 const price = Math.floor(Math.random() * 20) + 10; const camp = new Campground({ location: `${cities[random1000].city}, ${cities[random1000].state}`, title: `${sample(descriptors)} ${sample(places)}`, image: ‘https://source.unsplash.com/collection/483252/400x300‘, description: ‘so beautiful‘, price }) await camp.save(); } } //一定要记得运行这个! //运行之后断开mongoose连接 seedDB().then(() => { mongoose.connection.close(); })
views.show.ejs <% layout(‘layouts/boilerplate‘) %> <h1> <%=campground.title%> </h1> <h2> <%=campground.location%> </h2> <img src="<%= campground.image%>" > <p> <%= campground.description%> </p> <p> <a href="/campgrounds/<%=campground._id%>/edit">Edit</a> </p> <p> <form action="/campgrounds/<%=campground._id%>?_method=DELETE" method="POST"> <button>delete</button> </form> </p> <footer> <a href="/campgrounds">All</a> </footer> <!-- a link to return to the all campgrounds page -->
原文:https://www.cnblogs.com/LilyLiya/p/14401467.html