mongo-commands/index.js

51 lines
1.7 KiB
JavaScript
Raw Normal View History

2024-08-27 12:27:51 +03:00
const MDBClient = require('mongodb').MongoClient
const url = process.env.MONGO_URL
if (
!process.env.MONGO_URL ||
!process.env.DB_NAME ||
!process.env.COLLECTION_NAME ||
!process.env.COMMAND ||
!process.env.ARGUMENT
) {
2024-08-27 12:52:49 +03:00
throw new Error(`process.env.MONGO_URL ${process.env.MONGO_URL?.replace(/./ig, '*')}
2024-08-27 12:27:51 +03:00
process.env.DB_NAME ${process.env.DB_NAME}
process.env.COLLECTION_NAME ${process.env.COLLECTION_NAME}
process.env.COMMAND ${process.env.COMMAND}
process.env.ARGUMENT ${process.env.ARGUMENT}
Данные переменные окружения должны быть заполнены`)
}
const mongoDBConnect = async () => {
try {
const MongoClient = new MDBClient(url, {
useUnifiedTopology: true,
})
return await MongoClient.connect()
} catch (error) {
console.error(error)
}
}
2024-08-27 14:23:40 +03:00
console.log('try connect')
2024-08-27 12:27:51 +03:00
mongoDBConnect().then(async (client) => {
2024-08-27 14:23:40 +03:00
console.log('Connected to MongoDB')
try {
const db = await client.db(process.env.DB_NAME)
const collection = await db.collection(process.env.COLLECTION_NAME)
console.log('command', process.env.COMMAND)
console.log('argument', process.env.ARGUMENT, process.env.ARGUMENT.replace("ISODate()", `${new Date().toISOString()}`))
const answer = await collection[process.env.COMMAND](JSON.parse(process.env.ARGUMENT.replaceAll("ISODate()", `${new Date().toISOString()}`)))
await client.close();
return answer.ops?.[0] ?? answer
} catch (error) {
await client.close();
}
2024-08-27 12:27:51 +03:00
})
.then(console.log)
.catch(console.error)