mongo + mongoose的使用

安裝mongo

配置系統變量PATH mongo的bin所在路徑

任意位置執行 mongod --dbpath E:\mongodb\data(數據文件【文件夾data,安裝時讓指定的】我放在這個位置)

如下所示說明開啓成功

可視化工具選擇的是Robo 3T, 安裝方式網上自行百度

默認有test數據庫 ,下圖xss數據庫是自己命令行加的

🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵

創建自己的第一張表,

在已啓動mongo服務的情況下,命令行輸入 mongo

繼續輸入以下命令查看:

show dbs    // 你會看到默認的數據庫test

use AAA // 選擇數據庫,沒有則創建,此時雖然創建了,但還沒有數據,在show dbs結果中依然找不到新增的數據庫,除非你增了第一條數據

db.AAA.insert({age: 1,color: 'red'})

show dbs // 此時AAA表就出來了

Robo 3T 創建connect,並連接,

表需要手動刷新才能看到最新結果,後續自行查閱

🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵🔴🔵

node中使用:

npm 下載mongoose 模塊

// 在主文件中進行連接數據庫操作

const mongoose = require('mongoose');
var Schema = mongoose.Schema;
const bodyParser = require("body-parser");
const moment = require('moment');

// 此處xss是我自己創建的數據庫名 ,注意第二個參數,不然你可能會失敗,
mongoose.connect('mongodb://localhost/xss', { useNewUrlParser: true }, (err,res) => {
  if(!err) {
    console.log('連接成功')
  } else {
    console.log('連接失敗')
  }
});
// 定義表字段類型
var MySchema = new Schema({ name: String, color: String, sex: String, age: Number, createTime: String, _id: String}, {collation: 'data'});

// 這個項目作爲服務端,自定義接口方便其他項目調用 bodyParser是爲解決解析axios的POST請求參數讀不到問題
app.post('/cat/add', bodyParser.json(), function(req, res) {
  let params = req.body;
  let { name, color, sex, age } = params;
  var response = {
    "code": 200,
    "message": 'success'
  };
  var resErr = { // 自定義錯誤時返回response對象
    "code": 10000,
    "message": 'insert error'
  };
  const Cat = mongoose.model('Cat', MySchema);
  const kitty = new Cat({ id: new mongoose.Schema.Types.ObjectId, name, color, sex, age, createTime: moment().format('YYYY-MM-DD HH:mm:ss') });// moment可用可不用自行需要
  kitty.save((err, doc) => { // 數據庫保存
    if(!err) {
      res.end(JSON.stringify(response));
    } else {
      res.end(JSON.stringify(resErr));
    }
  });
})
// 查詢接口
app.post('/cat/list', bodyParser.json(), function(req, res) {
  var response = {
    "code": 200,
    "message": 'success'
  };

  const Cat = mongoose.model('Cat', MySchema);
// find的第二個參數,若設定則只返回該些字段,在node中雖然顯示,但客戶端是不會收到的,放心使用
  Cat.find({}, 'name color sex age createTime').sort({name: 1}).collation({locale: 'en_US', numericOrdering: true})
    .then(docs => {
    response.list = docs||[];
    res.end(JSON.stringify(response));
  })
})

 

附git地址: https://github.com/xss392795158/190801myserver.git   分支:   webpack4_react/master

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章