models.product.js includes the model we need to use
./models/product.js
const mongoose = require('mongoose'); const productSchema = new mongoose.Schema({ name: { type: String, required: true }, price: { type: Number, required: true, min: 0 }, category: { type: String, lowercase: true, enum: ['fruit', 'vegetable', 'dairy'] } }) const Product = mongoose.model('Product', productSchema); //export this model and then we can import it outside this file module.exports = Product;
seed.js是一个单独的js文件,专门用来添加更新到数据库中
seed.js
//一个单独的js,使用这个来添加一些数据到我们的数据库中 const mongoose = require('mongoose'); const Product = require('./models/product'); mongoose.connect('mongodb://localhost:27017/farmStand', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log("MONGO CONNECTION OPEN!!!") }) .catch(err => { console.log("OH NO MONGO CONNECTION ERROR!!!!") console.log(err) }) // const p = new Product({ // name: 'cake', // price: 2.99, // category: 'fruit' // }) // p.save().then(p => { // console.log(p) // }) // .catch(e => { // console.log(p) // }) const seedProducts = [ { name: 'Fairy Eggplant', price: 1.00, category: 'vegetable' }, { name: 'Organic Goddess Melon', price: 4.99, category: 'fruit' }, { name: 'Organic Mini Seedless Watermelon', price: 3.99, category: 'fruit' }, { name: 'Organic Celery', price: 1.50, category: 'vegetable' }, { name: 'Chocolate Whole Milk', price: 2.69, category: 'dairy' }, ] Product.insertMany(seedProducts) .then(res => { console.log(res) }) .catch(e => { console.log(e) })
index.js,主文件
index.js
const express = require('express'); const app = express(); const path = require('path'); const mongoose = require('mongoose'); const Product = require('./models/product'); mongoose.connect('mongodb://localhost:27017/farmStand', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log("MONGO CONNECTION OPEN!!!") }) .catch(err => { console.log("OH NO MONGO CONNECTION ERROR!!!!") console.log(err) }) app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(express.urlencoded({ extended: true }));//for app.post, read the body content app.get('/products', async (req, res) => { //use async and await to wait something call back to mongoose const products = await Product.find({}); res.render('products/index', { products }) //{products}供ejs里面调用 }) //should be above /products/:id, because the same format , will treat new as a id, which will trigger error app.get('/products/new', (req, res) => { res.render('products/new') }) app.post('/products', async (req, res) => { const newProduct = new Product(req.body) //create a new product await newProduct.save(); //save the new product res.redirect(`/products/${newProduct._id}`) }) app.get('/products/:id', async (req, res) => { const { id } = req.params; const product = await Product.findById(id); res.render('products/show', { product }) }) app.listen('3000', () => { console.log("APP IS LISTENING ON PORT 3000!") })
index.ejs: show product by their giving id. _id是mongoose自动生成的
index.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>All products</title> </head> <body> <h1>All products</h1> <ul> <%for(let product of products){%> <li> <a href="/products/<%= product._id%>"> <%= product.name %> </a> </li> <%}%> </ul> </body> </html>
show.ejs, 显示所有物品的详细信息
show.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> <%= product.name%> </title> </head> <body> <h1> <%= product.name%> </h1> <ul> <li>Price: $<%= product.price%> </li> <li>Category: <%= product.category%> </li> </ul> <a href="/products">All products</a> </body> </html>
new.ejs: 表单提交时间
<form action="/products" method="POST">
<button>Submit</button>
</form>
new.ejs<!-- Submit按钮一旦点击,提交页面/products, post,跟index.js里面的app.post('/products',。。。)连接着 -->
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>New product</title> </head> <body> <h1>Add a product </h1> <form action="/products" method="POST"> <label for="name">Name</label> <input type="text" name="name" id="name" placeholder="product name"> <label for="price">price</label> <input type="number" name="price" id="price" placeholder="price"> <label for="category">Select category</label> <select name="category" id="category"> <option value="fruit">fruit</option> <option value="vegetable">vegetable</option> <option value="dairy">dairy</option> </select> <button>Submit</button>
</form> </body> </html><!-- Submit按钮一旦点击,提交页面/products, post,跟index.js里面的app.post('/products',。。。)连接着 --> index.js中,凡是需要mongoose处理,需要等待时间的,都需要用asnyc and await进行操作。