1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| const MongoClient = require('mongodb').MongoClient; function _conection(callback) { var url = 'mongodb://localhost:27017/shuoshuo'; MongoClient.connect(url, (err, db) => { callback(err, db); }); } init(); //增加索引 function init() { _conection((err, db) => { db.collection('users').createIndex( {"username": 1}, null, (err, result) => { if (err) { console.error(err); return; } db.close(); } ); }); }
exports.insertMany = function (collectionName, json, callback) { _conection((err, db) => { db.collection(collectionName).insertMany(json, (err, result) => { callback(err, result); db.close(); }); }); }; exports.find = function (collectionName, json, C, D) { if (arguments.length == 3) { var callback = C; var limitAmount = 0; var skipAmount = 0; } else if (arguments.length == 4) { var callback = D; var args = C; var limitAmount = args.pageAmount || 0; var skipAmount = args.pageAmount * args.page || 0; var sort = args.sort || {}; } _conection((err, db) => { var tmp = db.collection(collectionName).find(json).limit(limitAmount).skip(skipAmount).sort(sort); tmp.toArray((err, docs) => { callback(err, docs); db.close(); }); }) }; exports.deleteMany = function (collectionName, json, callback) { _conection((err, db) => { db.collection(collectionName).deleteMany(json, (err, result) => { callback(err, result); db.close(); }); }); }; exports.update = function (collectionName, json1, json2, callback) { _conection((err, db) => { db.collection(collectionName).updateMany(json1, json2, (err, result) => { callback(err, result); db.close(); }); }); }; exports.getCount = function (collectionName, callback) { _conection((err, db) => { db.collection(collectionName).find().count().then((count) => { callback(count); }); }); };
|