次のページのサンプルを改造しました。
Quick Start
MongoDB にはユーザー scott パスワード tiger123 でアクセスできるとします。
データの挿入
mongodb_insert.js
#! /usr/bin/node
//// mongodb_insert.js//// May/03/2020// ----------------------------------------------------------------console.log("*** 開始 ***")consthost='scott:tiger123@localhost'constport=27017constMongoClient=require('mongodb').MongoClientconstassert=require('assert')consturl='mongodb://'+host+':'+port// Database NameconstdbName='myproject'constclient=newMongoClient(url,{useNewUrlParser:true,useUnifiedTopology:true})client.connect(function(err){assert.equal(null,err)console.log("Connected successfully to server")constdb=client.db(dbName)insertDocuments(db,function(){client.close()console.log("*** 終了 ***")})})// ----------------------------------------------------------------constinsertDocuments=function(db,callback){// Get the documents collectionconstcollection=db.collection('documents')// Insert some documentscollection.insertMany([{aa:10},{bb:20},{cc:30},{dd:40}],function(err,result){assert.equal(err,null)assert.equal(4,result.result.n)assert.equal(4,result.ops.length)console.log("Inserted 4 documents into the collection")callback(result)})}// ----------------------------------------------------------------
実行結果
$ export NODE_PATH=/usr/lib/node_modules
$ ./mongodb_insert.js
*** 開始 ***
Connected successfully to server
Inserted 4 documents into the collection
*** 終了 ***
データを読む
mongodb_read.js
#! /usr/bin/node
//// mongodb_read.js//// May/03/2020// ----------------------------------------------------------------console.log("*** 開始 ***")consthost='scott:tiger123@localhost'constport=27017constMongoClient=require('mongodb').MongoClientconstassert=require('assert')consturl='mongodb://'+host+':'+portconstdbName='myproject'constclient=newMongoClient(url,{useNewUrlParser:true,useUnifiedTopology:true})client.connect(function(err){assert.equal(null,err)console.log("Connected correctly to server")constdb=client.db(dbName)findDocuments(db,function(){client.close()console.log("*** 終了 ***")})})// ----------------------------------------------------------------constfindDocuments=function(db,callback){constcollection=db.collection('documents')collection.find({}).toArray(function(err,docs){assert.equal(err,null)console.log("Found the following records")console.log(docs)callback(docs)})}// ----------------------------------------------------------------
実行結果
$ export NODE_PATH=/usr/lib/node_modules
$ ./mongodb_read.js
*** 開始 ***
Connected correctly to server
Found the following records
[
{ _id: 5eafbfd5a6a9fb12219e7f50, aa: 10 },
{ _id: 5eafbfd5a6a9fb12219e7f51, bb: 20 },
{ _id: 5eafbfd5a6a9fb12219e7f52, cc: 30 },
{ _id: 5eafbfd5a6a9fb12219e7f53, dd: 40 }
]
*** 終了 ***