node链接mongoDB及封装

// 这个模块中封装所有对数据库的常用操作

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

function _connectDB(callback) {
  const url = "mongodb://127.0.0.1:27017"
  const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true }).connect((err, db) => {
    assert.equal(null, err)
    callback(err, db)
    console.log("链接服务成功")
  });
}

_connectDB(function () {
  // 表示链接成功之后做的事情
})

exports.insertOne = function (collectionName, json, callback) {
  _connectDB(function (err, db) {
    db.db("zmd").collection(collectionName).insertOne(json, function (err, result) {
      callback(err, result)
      db.close()
    })
  })
}

//调用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("插入成功")
  })
});

 

posted @ 2019-09-11 11:34  墨染清浅  阅读(687)  评论(0)    收藏  举报