Express + mongodb 웹 배경 인터페이스 개발

3933 단어 Express+mongo
  • Express 개발 웹 인터페이스 Express 는 nodejs, 빠 르 고 개방 적 이 며 간단 한 웹 개발 프레임 워 크
    //   express
    npm install express--save
    // server.js
    const express = require('express')
    
    //   app
    const app = express()
    
    app.get('/', function(req, res){
      res.send('

    Hello world

    ') }) app.listen(3000, function(){ console.log('Node app start at port 3000') }) // server.js node server.js // http://localhost:3000 Hello world
    //       
    // server.js
    const express = require('express')
    
    //   app
    const app = express()
    
    app.get('/', function(req, res){
      res.send('

    Hello world

    ') }) app.get('/data', function(req, res){ res.json({user: 'Edison', age: 20}) }) app.listen(3000, function(){ console.log('Node app start at port 3000') }) // http://localhost:3000/data
    를 기반 으로 명령 행 에서 node server. js 를 다시 실행 해 야 합 니 다. 중복 작업 을 하지 않 기 위해 nodemon:
    //   nodemon
    npm install nodemon--save
    을 server. js 파일 동급 디 렉 터 리 명령 행 에 설치 합 니 다. nodemon server. js,이후 수정 데이터 자동 업데이트 localhost: 3000 
  • 비 관계 형 데이터베이스 mongodb 에 mongodb 를 설치 하고 관리자 신분 으로 cmd 명령 행 을 실행 하 며 mongodb \ 빈 디 렉 터 리 에서 mongo 를 실행 합 니 다. 다음 과 같은 코드 가 실행 성공
    F:\>cd F:\workTool\mongodb\bin
    
    F:\workTool\mongodb\bin>mongo
    MongoDB shell version v4.0.5
    connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
    Implicit session: session { "id" : UUID("df58d557-2e9f-4508-a1db-98cdfb83847d") }
    MongoDB server version: 4.0.5
    Server has startup warnings:
    2019-01-21T09:05:01.710+0800 I CONTROL  [initandlisten]
    2019-01-21T09:05:01.710+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
    2019-01-21T09:05:01.710+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
    2019-01-21T09:05:01.710+0800 I CONTROL  [initandlisten]
    ---
    Enable MongoDB's free cloud-based monitoring service, which will then receive and display
    metrics about your deployment (disk utilization, CPU, operation statistics, etc).
    
    The monitoring data will be available on a MongoDB website with a unique URL accessible to you
    and anyone you share the URL with. MongoDB may use this information to make product
    improvements and to suggest MongoDB products and deployment options to you.
    
    To enable free monitoring, run the following command: db.enableFreeMonitoring()
    To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
     
  • nodejs 의 mongoose 모듈 링크 와 mongodb 링크 mongo 를 사용 하고 Edison 이라는 집합 을 사용 합 니 다.
    const DB_URL = 'mongodb://127.0.0.1:27017/Edison'
    mongoose.connect(DB_URL)
    mongoose.connection.on('connected', function(){
      console.log('mongo connect success')
    })
    작성 표 는 my sql 과 유사 합 니 다. mongo 에는 문서, 필드 의 개념
    const User = mongoose.model('user', new mongoose.Schema({
      user: {type: String, require: true},
      age: {type: Number, require: true}
    }))
    이 추가 되 었 습 니 다.
    //     
    User.create({
      user: 'Edison',
      age: 20
    }, function(err, doc){
      if (!err) {
        console.log(doc)
      } else {
        console.log(err)
      }
    })
    데 이 터 를 찾 습 니 다.
    app.get('/data', function(req, res){
      User.find({}, function(err, doc){
        res.json(doc)
      })
    })
    
    //     
    app.get('/data', function(req, res){
      User.findOne({}, function(err, doc){
        res.json(doc)
      })
    })
    데 이 터 를 삭제 합 니 다.
    User.remove({age: 20}, function(err, doc){
      if (!err) {
        console.log(doc)
      } else {
        console.log(err)
      }
    })
    수정 데이터:
    //     
    User.update({'user': 'Edison'}, {'$set': {age: 26}}, function(err, doc){
      console.log(doc)
    })
     
  • 좋은 웹페이지 즐겨찾기