task-svr/src/scripts/initdata.ts
2024-10-16 16:34:39 +08:00

32 lines
1.1 KiB
TypeScript

import mongoose from 'mongoose'
import * as dotenv from 'dotenv'
const envFile = process.env.NODE_ENV && process.env.NODE_ENV === 'production' ? `.env.production` : '.env.development'
dotenv.config({ path: envFile })
console.log(process.env.DB_MAIN)
const dir = `${__dirname}/../initdatas`
const db = mongoose.connection
var ejson = require('mongodb-extended-json')
;(async () => {
try {
await mongoose.connect(process.env.DB_MAIN)
const fs = require('fs') // Used to get all the files in a directory
const list = fs.readdirSync(dir)
for (var i = 0; i < list.length; i++) {
if (list[i].endsWith('.json') === false) {
continue
}
// Remove the file extension
const collection_name = list[i].replace('.json', '')
const parsedJSON = require(dir + '/' + list[i])
const jsonArry = ejson.deserialize(parsedJSON)
await db.collection(collection_name).insertMany(jsonArry)
console.log('Inserted ' + jsonArry.length + ' documents into the "' + collection_name + '" collection.')
}
console.log('Finished inserting documents into the database')
} catch (e) {
console.log(e)
}
process.exit(0)
})()