Node.js 與 MongoDB 交互 【創建多個鏈接】

1、安裝MongoDB

  下載mongoDB  https://www.mongodb.com/download-center?jmp=nav#atlas node

 

  安裝完成後,配置環境變量 PATH 中加入「C:\Program Files\MongoDB 2.6 Standard\bin「  //按你安裝的路徑更改mongodb

  找個地方建立兩個文件夾,例如:C:\M_DB、C:\M_LOG 分別存放數據庫文件和日誌文件數據庫

  打開目錄「C:\Program Files\MongoDB 2.6 Standard\bin」,並在此目錄下新建一個mongo.config文件,文件內容如npm

  ##數據庫目錄
  dbpath=C:\M_DB

  ##日誌輸出文件
  logpath=C:\M_LOG\mongodb.log
  以管理員方式打開CMD窗口,運行以下命令安裝MongoDB服務 1  
   
  mongod --config "C:\Program Files\MongoDB 2.6 Standard\bin\mongo.config" --install
  
  net start mongodb

  mongo

  以管理員方式打開CMD窗口,運行以下命令安裝MongoDB服務 2
  cd C:\Program Files\MongoDB 2.6 Standard\bin

  mongod.exe --dbpath "C:\M_DB" --logpath "C:\M_LOG\mongodb.log"
 

2、Node.js 配合 Mongoose 【創建多個鏈接】

  npm install mongoose --save

  
  一、根目錄下建立 mongoose 文件夾 ,文件夾下創建鏈接文件 db.js
/** 
 * Created by cunkuan on 2017/10/13.
 */

var mongoose = require('mongoose'),
    DB_URL1 = 'mongodb://127.0.0.1:27017/node-db',
  DB_URL2 = 'mongodb://192.168.0.24:27017/other-db'  


/**
 * nodeMobile庫鏈接 可創建多個鏈接庫
 */
mongoose.Promise = global.Promise;
var nodeDB = mongoose.createConnection(DB_URL1,{ useMongoClient: true });
var otherDB = mongoose.createConnection(DB_URL2,{ useMongoClient: true });


/**
 * 鏈接成功
 */
mongoose.connection.on('connected', function () {
    console.log('Mongoose connection open to ' + DB_URL);
});

/**
 * 鏈接異常
 */
mongoose.connection.on('error',function (err) {
    console.log('Mongoose connection error: ' + err);
});

/**
 * 鏈接斷開
 */
mongoose.connection.on('disconnected', function () {
    console.log('Mongoose connection disconnected');
});

exports.nodeDB = nodeDB;
exports.otherDB = otherDB;
  

 二、根目錄下建立 schema 文件夾 例如:建立獎品表 schema 文件夾下 建立獎品表(lucydrawSchema.js 數據模型)
/**
 * 獎品信息
 */
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var db = require('../mongoose/db');

//獎品
var drawList = new Schema({
    drawName: {type: String},//名稱
    drawGrade: {type: Number},//獎品等級
    drawCount: {type: Number},//獎品數量
    drawProbability: {type: Number},//獎品機率
});

//活動
var LucyDraw = new Schema({
    name: {type: String},
    startTime: {type: Date, default: Date.now},
    endTime: {type: Date, default: Date.now},
    desc:{type: String},
    countType:{type: String},
    count:{type: Number},
    effect:{type: Boolean},
    drawList: [drawList],
});


module.exports = db.nodeDB.model('LucyDraw', LucyDraw);

  

  三、routes 文件夾下,建立路由文件 lucydrawRoutes.js (passport 是 用於權限驗證的json

var passport = require('passport');

var LucyDraw = require("../schema/lucydrawSchema");

exports.pcRouter = function (router) {

    /**
     * 新建抽獎
     */
    router.post('/addlucydraw', passport.authenticate('bearerPC', {session: false}), function (req, res, next) {
        var data = req.body;
        var lucyDrawObj = new LucyDraw(data);
        lucyDrawObj.save(function (err, result) {
            if (err) {
                res.json({
                    code: '500',
                    msg: "Error:" + err
                });
            } else {
                res.json({
                    code: '0',
                    result: result
                });
            }
        })
    });

    /**
     * 抽獎列表
     */
    router.get('/lucydrawlist', passport.authenticate('bearerPC', {session: false}), function (req, res, next) {
        var page = req.query.page || 0;
        var size = req.query.size || 10;
        var query = LucyDraw.find({});
        query.limit(parseInt(page));
        query.skip(parseInt(page) * parseInt(size));
        query.sort({createTime: 1});
        query.exec(function (err, result) {
            if (err) {
                res.json({
                    code: '500',
                    msg: "Error: 服務器錯誤"
                });
            } else {
                res.json({
                    code: '0',
                    result: result
                });
            }
        });
    });

    /**
     * 抽獎查詢
     */
    router.get('/lucydraw', passport.authenticate('bearerPC', {session: false}), function (req, res, next) {
        var id = req.query.id;
        LucyDraw.findOne({_id:id},function (err,result) {
            if (err) {
                res.json({
                    code: '500',
                    msg: "Error: 服務器錯誤"
                });
            } else {
                res.json({
                    code: '0',
                    result: result
                });
            }
        });
    });

    /**
     * 抽獎編輯
     */
    router.put('/lucydraw', passport.authenticate('bearerPC', {session: false}), function (req, res, next) {
        var id = req.query.id;
        var data = req.body;
        LucyDraw.update({_id:id},data,function (err,result) {
            if (err) {
                res.json({
                    code: '500',
                    msg: "Error: 服務器錯誤"
                });
            } else {
                res.json({
                    code: '0',
                    result: result
                });
            }
        });
    });

    /**
     * 抽獎上下架
     */
    router.put('/lucydraw_effect', passport.authenticate('bearerPC', {session: false}), function (req, res, next) {
        var id = req.query.id;
        var effect = req.query.effect;
        LucyDraw.update({_id:id},{effect:effect},function (err,result) {
            if (err) {
                res.json({
                    code: '500',
                    msg: "Error: 服務器錯誤"
                });
            } else {
                res.json({
                    code: '0',
                    result: result
                });
            }
        });
    });

};

 

  四、app.js 添加代碼api

var lucydrawRoutes= require('./routes/lucydrawRoutes');

....
....
....


app.use('/api/lucydraw',lucydrawRoutes);
相關文章
相關標籤/搜索