node link mongoDB and packaging

// this module encapsulates all of the common database operations 

const MongoClient = the require ( 'MongoDB' ) .MongoClient; 
const Assert = the require ( 'Assert' ); 

function _connectDB (the callback) { 
  const URL = "MongoDB: //127.0. 0.1: 27017 " 
  const Client = new new MongoClient (URL, {useNewUrlParser: to true , useUnifiedTopology: to true }). Connect ((ERR, DB) => { 
    assert.equal ( null , ERR) 
    the callback (ERR, DB) 
    the console.log ( "success link service" ) 
  }); 
} 

_connectDB ( function () {
   //After indicates a successful link do something 
}) 

exports.insertOne = function (collectionName, json, callback) { 
  _connectDB ( function (ERR, db) { 
    db.db ( "ZMD"). Collection (collectionName) .insertOne (json, function (ERR, Result) { 
      the callback (ERR, Result) 
      db.Close () 
    }) 
  }) 
}

// method call insertOne

var db = require("../models/db.js")

/* GET users listing. */
router.get('/', function(req, res, next) {
  // res.send('respond with a resource');
  db.insertOne("teacher",{name:"teacherZhang"},function(err,result){
    if(err){
      console.log("插入失败")
      return
    }
    res.send("插入成功")
  })
});

 

Guess you like

Origin www.cnblogs.com/zmdblog/p/11505323.html