プログラム
mongo_read.js
// ----------------------------------------------------------------
// mongo_read.js
//
// Jun/27/2024
// ----------------------------------------------------------------
const mongoose = require('mongoose')
console.error ("*** 開始 ***")
// MongoDB コネクションの設定
const mongoURI = 'mongodb://localhost:27017/city'
// MongoDB への接続
mongoose.connect(mongoURI)
// 接続が確立された時のコールバック
const db = mongoose.connection
db.on('connected', function() {
console.log('MongoDBに接続しました')
})
// データのスキーマ定義
const citySchema = new mongoose.Schema({
id: String,
name: String,
population: Number,
date_mod: Date
})
// モデルの作成
const City = mongoose.model('City', citySchema, 'saitama')
// データの取得
const getCities = async () => {
try {
const cities = await City.find()
for (it in cities)
{
const obj_city = cities[it]
const json_str = JSON.stringify(obj_city)
const city = JSON.parse(json_str)
var str_out = city.id + "\t" + city.name
str_out += "\t" + city.population
str_out += "\t" + city.date_mod
console.log (str_out)
}
} catch (error) {
console.error('データの取得に失敗しました', error)
} finally {
// 接続の切断
mongoose.connection.close()
console.error ("*** 終了 ***")
}
}
// ----------------------------------------------------------------
getCities()
// ----------------------------------------------------------------
実行
コマンド
go_read.sh
xport NODE_PATH=/usr/local/lib/node_modules
node mongo_read.js
実行結果
$ ./go_read.sh
*** 開始 ***
MongoDBに接続しました
t1161 さいたま 93154 1950-07-22T14:00:00.000Z
t1162 所沢 28657 1950-05-14T14:00:00.000Z
t1163 越谷 97421 1950-10-01T15:00:00.000Z
t1164 久喜 31864 1950-06-17T14:00:00.000Z
t1165 熊谷 49358 1950-08-13T14:00:00.000Z
t1166 秩父 65792 1950-09-11T15:00:00.000Z
t1167 川越 37256 1950-07-04T14:00:00.000Z
t1168 和光 52384 1950-04-19T15:00:00.000Z
t1169 新座 26897 1950-06-23T14:00:00.000Z
*** 終了 ***