zoukankan      html  css  js  c++  java
  • 0_campgrounds CRUD

    refer to: https://www.udemy.com/course/the-web-developer-bootcamp

    1. npm init -y
    2. npm i express mongoose ejs
    3. npm i method-override
    4. nodemon app.js
    5. nodemon seeds/index.js
    models/campgrounds.js

    const mongoose = require('mongoose'); const Schema = mongoose.Schema; const CampgroundSchema = new Schema({ title: String, Price: String, description: String, location: String }); module.exports = mongoose.model('Campground', CampgroundSchema);
    app.js

    const express = require('express') const path = require('path'); const mongoose = require('mongoose'); const Campground = require('./models/campground'); const methodOverride = require('method-override');//need npm i method-override firstly, for post/delete 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"); }); const app = express(); app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')) app.use(express.urlencoded({ extended: true })) app.use(methodOverride('_method')) //for post/delete // in edit.ejs <form action="/campgrounds/<%=campground._id%>?_method=PUT" method="POST"> app.get('/', (req, res) => { res.send('home') }) //create a new Campground with one info inserted // app.get('/makecampground', async (req, res) => { // const camp = new Campground({ title: 'my backyard', description: 'cheap camping' }); // await camp.save(); // res.send(camp) // }) app.get('/campgrounds', async (req, res) => { const campgrounds = await Campground.find({}); res.render('campgrounds/index', { campgrounds }) }) app.get('/campgrounds/new', (req, res) => { res.render('campgrounds/new') }) //need app.use(express.urlencoded({ extended: true })) //linked to edit.ejs <form action="/campgrounds/<%=campground._id%>?_method=PUT" method="POST"> app.post('/campgrounds', async (req, res) => { // res.send(req.body); output: {"campground":{"title":"akhda","location":"skjdks"}} const campground = new Campground(req.body.campground); await campground.save(); res.redirect(`/campgrounds/${campground._id}`) }) app.get('/campgrounds/:id', async (req, res) => { const campground = await Campground.findById(req.params.id); res.render('campgrounds/show', { campground }) }) app.get('/campgrounds/:id/edit', async (req, res) => { const campground = await Campground.findById(req.params.id); res.render('campgrounds/edit', { campground }) }) app.put('/campgrounds/:id', async (req, res) => { // res.send('worked!') this is for first time testing const { id } = req.params; const campground = await Campground.findByIdAndUpdate(id, { ...req.body.campground }) //new:true can be added res.redirect(`/campgrounds/${campground._id}`) //return to the updated info page }) app.delete('/campgrounds/:id', async (req, res) => { // res.send('worked!') this is for first time testing const { id } = req.params; await Campground.findByIdAndDelete(id); //new:true can be added res.redirect('/campgrounds') //return to the updated info page }) app.listen(3030, () => { console.log('Serving on port 3030') })
    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"); }); //添加单条信息~ // const seedDB = async () => { // await Campground.deleteMany({});//删除之前的记录 // const c = new Campground({ title: 'purple field' });//添加新记录 // await c.save();//保存 // } // 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 camp = new Campground({ location: `${cities[random1000].city}, ${cities[random1000].state}`, title: `${sample(descriptors)} ${sample(places)}` }) await camp.save(); } } //一定要记得运行这个! //运行之后断开mongoose连接 seedDB().then(() => { mongoose.connection.close(); })
    index.ejs
    
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>campgrounds</title>
    </head>
    
    <body>
        <h1>all grounds</h1>
        <div>
            <a href="/campgrounds/new">Add</a>
        </div>
        <ul>
            <%for(let campground of campgrounds){%>
                <li>
                    <a href="/campgrounds/<%=campground._id%>">
                        <%=campground.title%>
                    </a>
                </li>
                <%}%>
        </ul>
    
    </body>
    
    </html>
    show.ejs
    
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Show</title>
    </head>
    
    <body>
        <h1>
            <%=campground.title%>
        </h1>
        <h2>
            <%=campground.location%>
        </h2>
        <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 -->
    
    </body>
    
    </html>
    new.ejs
    
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>New campground</title>
    </head>
    
    <body>
        <form action="/campgrounds" method="POST">
            <div>
                <label for="title">Title</label>
                <input type="text" id="titel" name="campground[title]">
            </div>
    
            <div>
                <label for="location">Location</label>
                <input type="text" id="location" name="campground[location]">
            </div>
            <button>Add</button>
        </form>
        <a href="/campgrounds">All</a>
    
    </body>
    
    </html>
    edit.ejs
    
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Edit campground</title>
    </head>
    
    <body>
        <h1>Edit campground</h1>
        <form action="/campgrounds/<%=campground._id%>?_method=PUT" method="POST">
            <div>
                <label for="title">Title</label>
                <input type="text" id="titel" name="campground[title]" value="<%=campground.title%>">
                <!-- value = value="<%=campground.title%>, 默认值(待编辑信息)填充 -->
            </div>
    
            <div>
                <label for="location">Location</label>
                <input type="text" id="location" name="campground[location]" value="<%=campground.location%>">
            </div>
            <button>save</button>
        </form>
        <a href="/campgrounds/<%=campground._id%>">Back to campground</a>
    
    </body>
    
    </html>
  • 相关阅读:
    别以为真懂Openstack: 虚拟机创建的50个步骤和100个知识点(3)
    别以为真懂Openstack: 虚拟机创建的50个步骤和100个知识点(2)
    别以为真懂Openstack: 虚拟机创建的50个步骤和100个知识点(1)
    High Availability手册(3): 配置
    High Availability手册(2): 架构
    High Availability手册(1): 环境
    Data Center(5): 实例
    Data Center手册(4):设计
    Data Center手册(3): Load Balancer
    了解美杜莎(Medusa)
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14400190.html
Copyright © 2011-2022 走看看