53 lines
No EOL
1.4 KiB
JavaScript
53 lines
No EOL
1.4 KiB
JavaScript
const { MongoClient } = require('mongodb')
|
|
require('dotenv').config()
|
|
|
|
const mongoURI = process.env.MONGO_URI
|
|
|
|
if(!mongoURI){
|
|
console.error('URI Not Loaded !')
|
|
process.exit(1)
|
|
}
|
|
|
|
const client = new MongoClient(mongoURI)
|
|
|
|
async function connect(){
|
|
try{
|
|
await client.connect()
|
|
console.log("Client connecté")
|
|
return client.db("shopping")
|
|
}
|
|
catch(err){
|
|
console.error("ERREUR DE CONNEXION : ", err)
|
|
return "Connexion failed"
|
|
}
|
|
}
|
|
async function playwithDoc(){
|
|
const db = await connect()
|
|
if(typeof db === 'string'){
|
|
console.error(db)
|
|
process.exit(1)
|
|
}
|
|
const collection = db.collection("Users")
|
|
const insertResult = await collection.insertOne({
|
|
name: "Jérémy"
|
|
})
|
|
console.log("Document inséré : ", insertResult)
|
|
const search = await collection.find({name: 'Jérémy'}).toArray()
|
|
console.log(" Search is : ", search)
|
|
const update = await collection.updateOne({name: 'Jérémy'}, { $set: { age : 32} })
|
|
console.log(" result update : ", update)
|
|
const newSearch = await collection.find({name: 'Jérémy'}).toArray()
|
|
console.log(" Search updated is : ", newSearch)
|
|
const deleteone = await collection.deleteMany({name: 'Jérémy'})
|
|
console.log(" Delete result is : ", deleteone)
|
|
await client.close()
|
|
}
|
|
|
|
(async () => {
|
|
try{
|
|
await playwithDoc()
|
|
}
|
|
catch (err){
|
|
console.error(err)
|
|
}
|
|
})() |