完整程式碼,請洽: https://github.com/Zrn-code/Node-js-tutorial/tree/node-09
# mongoose
# 安裝 mongoose
# 連結 MongoDB
app.js | const mongoose = require('mongoose'); |
| |
| const dbURI = 'mongodb+srv://zrn:<password>@note.ag3er.mongodb.net/<dbname>?retryWrites=true&w=majority'; |
| mongoose.connect( dbURI ,{useNewUrlParser: true, useUnifiedTopology: true}) |
| .then((result)=> app.listen(3000)) |
| .catch((err)=> console.log(err)); |
blog.js | |
| const mongoose = require('mongoose'); |
| const Schema = mongoose.Schema; |
| const blogSchema = new Schema({ |
| title: { |
| type: String, |
| required: true |
| }, |
| snippet: { |
| type: String, |
| required: true |
| }, |
| body: { |
| type: String, |
| required: true |
| } |
| },{ timestamps: true }) |
| const Blog = mongoose.model('Blog',blogSchema); |
| |
| module.exports = Blog; |
# 使用與儲存資料
# 儲存資料
app.js | const Blog = require('./models/blog'); |
| app.get('/add-blog',(req,res)=>{ |
| |
| const blog = new Blog({ |
| title: 'new blog', |
| snippet: 'about my new blog', |
| body: 'more about my new blog' |
| }); |
| blog.save() |
| .then((result) => res.send(result)) |
| .catch((err) => console.log(err)); |
| }); |
# 使用資料
app.js | app.get('/all-blogs',(req, res) =>{ |
| |
| Blog.find() |
| .then((result)=> res.send(result)) |
| .catch((err)=>(console.log(err))); |
| }); |
# 展示資料到頁面中
app.js | app.get('/',(req,res)=>{ |
| res.redirect('/blogs'); |
| }); |
| app.get('/blogs',(req,res)=>{ |
| Blog.find() |
| .then((result)=> |
| res.render('index',{ title: 'All Blogs', blogs: result})) |
| .catch(err)=> console.log(err); |
| }); |