monoose

MongoDB安裝教程

1:啓動

net start MongoDB

2:項目安裝

npm i mongoose

3:可視化工具安裝
下載地址

4:根目錄建立dbs文件夾

5:在dbs文件夾建立配置文件config.js,然後在文件下建立目錄models.
config.js 數據庫連接

module.exports = {
    dbs: 'mongodb://127.0.0.1:27017/dbs'
}

在models文件夾下面建立person.js文件
person.js 相當於數據庫的操作模型文件,代表一張表

const mongoose = require('mongoose')

let personSchema = new mongoose.Schema({
    name: String,
    age: Number
})

module.exports = mongoose.model('Person', personSchema)

6:在app.js中引入

const mongoose = require('mongoose')
const dbConfig = require('./dbs/config')

mongoose.connect(dbConfig.dbs, {
  useNewUrlParser: true
})

7:在user.js中示例:增刪改查

const Person = require('../dbs/models/person')

//增加
router.post('/addPerson', async function (ctx) {
  const person = new Person({ name: ctx.request.body.name, age: ctx.request.body.age })
  let code
  try {
    await person.save()
    code = 0
  } catch (error) {
    code = -1
  }
  ctx.body = {
    code: code
  }
})

//修改
router.post('/updatePerson', async function (ctx) {
  const result = await Person.where({
    name: ctx.request.body.name
  }).update({
    age: ctx.request.body.age
  })
  ctx.body = {
    code: 0
  }
})
//查詢
router.post('/getPerson', async function (ctx) {
  const result = await Person.findOne({ name: ctx.request.body.name })
  const results = await Person.find({ name: ctx.request.body.name })
  ctx.body = {
    code: 0,
    result,
    results
  }
})
//刪除
router.post('/removePerson', async function (ctx) {
  const result = await Person.where({
    name: ctx.request.body.name
  }).remove({
    age: ctx.request.body.age
  })
  ctx.body = {
    code: 0
  }
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章