Node MongoDB

Reference Link MongoDB – JWT

连接 Mongo

在 Mongo Db Atlas创建一个 collections, 生成链接

const mongoose = require('mongoose');

mongoose.connect(dbURI, {useNewUrlParse: true, useUnifiedTopology: true}).then(res => app.listen(3000)).catch(err => console.log(err))

2 定义schma model

const Schema = mongoose.Schema;
// schema 定义结构
const blogSchema = new Schema({
  title: {type: String, require: true},
  body: {type: String, require: true}
}, {timeStamps: true})

//model 操作数据
const Blog = mongoose.model('Blog', blogSchema);
module.exports = Blog;

Getting and save Data

// Blog import 上面 
app.get('/add-blog', (req, res) => {
  const blog = new Blog({
     title: 'xx',
     body: 'this is body'
  })
  blog.save().then()
})

// get all blog
app.get('all-blogs', (req, res) => {
   Blog.find().then(result => res.send(result))
})
// get one 
Blog.findById('xxxx').then

Leave a Reply

Your email address will not be published. Required fields are marked *