| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
lsch9594
9年前发布

NodeJS中使用MongoDB的简单封装

使用示例    

/*   使用示例:  */  var DB = require('./DB.js').DB;  var ObjectId = require('mongodb').ObjectID;  var docName = 'User';  DB(docName, function (db, collection) {   collection.bulkWrite([{insertOne:{document:message}}], function (err, result) {    assert.equal(null, err);    invokeCallback.call(callback, result);    db.close();   });  });  

连接封装部分    

var mongo = require('mongodb').MongoClient;  var assert = require('assert');    var url = 'mongodb://localhost:27017/test';    module.exports.DB = function (name, callback) {      mongo.connect(url, function (err, db) {          assert.equal(null, err);          var collection = db.collection(name);          if (typeof collection === 'undefined') {              db.createCollection(name);              collection = db.collection(name);          }          if (typeof callback === 'function') {              callback(db, collection);          }      });  };