Db.use.js
1 /**2 * Before use: Install node environment, Express, MongoDB first.3 * 4 * 1.1 Install node5 * 1.2 npm i-d Express MongoDB && npm I-g Express MongoDB6 * 1.3 db.action: Add, delete, check, change (currently only added as an example), Db.config: The configuration database connection name also has an IP address and port number.7 */8 9Const EXPRESS = require (' Express ');TenConst APP =Express (); OneConst DB = require ('./db.action ')); AConst DBCONFIG = require ('./db.config ')); - -App.get ('/',function(req, res) { the - //inserting more than one data - Db.insertmany (Dbconfig.dbname, [ -{' name ': ' Little Blue ', ' age ': ' Home ': ' Chenzhou ' }, +{' name ': ' Little green ', ' age ': +, ' home ': ' Yongzhou ' }, -{' name ': ' Little Red ', ' age ': ' Home ': ' Beijing ' } +],function(err, result) { A if(ERR)Throwerr; atRes.send (' Insert succeeded '); - //db.close (); - }); - -}). Listen (80);
Db.config.js
1 //Database name2Let dbname = ' test ';3 4 //IP Address5Let IP = ' 127.0.0.1 ';6 7 //Port number8Let port = 27017;9 Ten One //ES5 Export. AModule.exports = { -URL: ' mongodb://' + IP + ': ' + port + '/', - Dbname:dbname the } - - //ES6 Export - //export {url,db};
Db.action.js
1 //Import {url,db} from './db.config ' ES6;2(function () {3Const Mongoclient = require (' MongoDB '). mongoclient;4Const DBCONFIG = require ('./db.config '));5 6 function_connectdb (callback) {7Let Dburl =Dbconfig.url;8Let dbname =Dbconfig.dbname;9 //Link DatabaseTenMongoclient.connect (Dburl + dbname,function(err, db) { One callback (err, DB); A }); - } - the //inserting A single piece of data -Exports.insertone =function(CollectionName, data, callback) { -_connectdb (function(err, db) { - + if(err) { - callback (err, DB); + return; A } at -db =db.db (collectionname); - -Db.collection (Db.databasename). Insertone (Data,function(err, result) { - callback (err, result); - //Db.close (); Close the database in }); - }); to } + - the //inserting more than one data *Exports.insertmany =function(CollectionName, data, callback) { $_connectdb (function(err, db) {Panax Notoginseng if(err) { - callback (err, DB); the return; + } A thedb =db.db (collectionname); + -Db.collection (CollectionName). Insertmany (Data,function(err, result) { $ callback (err, result); $ //Db.close (); Close the database - }); - }); the } -})()
MongoDB-Inserting data