云萌主云应用官方论坛
标题:
NodeJS中使用MongoDB的简单封装
[打印本页]
作者:
lady-niuniu
时间:
2016-12-30 01:01
标题:
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);
}
});
};
复制代码
来源:
http://www.open-open.com/code/view/1454897340917
欢迎光临 云萌主云应用官方论坛 (https://yunmengzhu.com/)
Powered by Discuz! X3.4