0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

プログラム

mongo_update.ts
// ----------------------------------------------------------------
//      mongo_update.ts
//
//                                              Jun/28/2024
// ----------------------------------------------------------------
import mongoose from 'mongoose'

// ----------------------------------------------------------------
function get_current_date_proc(): string {
  const today = new Date()
  const ddx =
    today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate()
  return ddx
}

// ----------------------------------------------------------------
console.error("*** 開始 ***")
// MongoDB コネクションの設定
const mongoURI:string = 'mongodb://localhost:27017/city'

// MongoDB への接続
mongoose.connect(mongoURI)

// 接続が確立された時のコールバック
const db = mongoose.connection
db.on('connected', () => {
  console.log('MongoDBに接続しました')
})

const citySchema = new mongoose.Schema<CitySchema>({
  id: String,
  name: String,
  population: Number,
  date_mod: Date,
})

// モデルの作成
const City = mongoose.model<CitySchema>('City', citySchema, 'saitama')

const updateCities = async (id_in: string, population_in: number) => {
  try {
    console.log('*** updateCities bbb ***')
    const ddx:string = get_current_date_proc()

    await City.updateOne({ id: id_in }, {
      population: population_in,
      date_mod: new Date(ddx),
    })
  } catch (error) {
    console.error('データの更新に失敗しました', error)
  } finally {
    // 接続の切断
    mongoose.connection.close()
    console.error('*** 終了 ***')
  }
}

// ----------------------------------------------------------------
const id:string = process.argv[2]
const population_in:number = parseInt(process.argv[3])
console.log(id + '\t' + population_in)
updateCities(id, population_in)
// ----------------------------------------------------------------

実行コマンド

bun run mongo_update.ts t1167 9120000
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?