ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Mongoose with express-1

2021-02-11 08:01:28  阅读:147  来源: 互联网

标签:product const log express Mongoose products mongoose console


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

<!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>
        <!-- Submit按钮一旦点击,提交页面/products, post,跟index.js里面的app.post('/products',。。。)连接着 -->  
    </form>
</body>

</html>
<!-- Submit按钮一旦点击,提交页面/products, post,跟index.js里面的app.post('/products',。。。)连接着 -->   index.js中,凡是需要mongoose处理,需要等待时间的,都需要用asnyc and await进行操作。      

标签:product,const,log,express,Mongoose,products,mongoose,console
来源: https://www.cnblogs.com/LilyLiya/p/14397232.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有