នៅ​ក្នុង​មូលដ្ឋាន​ទិន្នន័យ​ MongoDB បើ​សិន​ជា​យើង​ចង់​កែប្រែ​ទិន្នន័យ​ដែលជា​ឯកសារ​ណាមួយ​ យើងចាំបាច់​ត្រូវ​​ប្រើប្រាស់​វិធី​ឈ្មោះ updateOne() ដោយ​ធ្វើ​ដូច​ខាង​ក្រោម​នេះ៖

 

import express from 'express'
import path from 'path'

const app = express()
const port = process.env.PORT || 3000
const __dirname = path.resolve()
 
import index from './routes/index.js'
import backend from './routes/backend.js'
import mydb from './models/connectMongoDB.js'

app.use('/',async function(req,res,next){
    req.mydb = await mydb
    req.__dirname = __dirname
    next()
})

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(express.static(path.join(__dirname, 'public')))
app.use(express.urlencoded({extended:false}))
app.use(express.json())
                                  
app.use('/',index) 
app.use('/backend',backend) 

app.listen(port,function(){
    console.log(`This application is listening to the port: ${port}`)
})

 

/* ./routes/index.js */
import express from 'express'
import func from '../models/mongodb.js'
const index = express.Router()

index.use(func)

index.get('/',(req,res)=>{
    res.render('base',req.data)
})
 
export default index

 

//models/mongodb.js

function func(req,res,next){
    let myquery = { name:/^Tin Ch/}
    let newvalue = { $set: {name: "Hin Channiroth"} }

    req.mydb.collection("users").updateOne(myquery,newvalue,function(err){
        if (err) throw err
        req.mydb.collection("users").findOne({name:/^Hin/},function(err, result){
            if (err) throw err
            req.data = {}
            req.data.message = JSON.stringify(result)
            next()
        })
        
    })
}

export default func

 

យ៉ាងណាម៉ិញ បើសិន​ជា​យើង​មានបំណងចង់កែប្រែទិន្នន័យ​លើ​ស​ពី​មួយ យើង​ចាំបាច់​ត្រូវ​យក​វិធី​ឈ្មោះ updateMany() មក​ប្រើ​ ដោយ​ធ្វើ​ដូច​ខាង​ក្រោម​នេះ៖

 

//models/mongodb.js

function func(req,res,next){
    let myquery = { name:/^Tin/}
    let newvalue = { $set: {name: "Keo Komrong"} }

    req.mydb.collection("users").updateMany(myquery,newvalue,function(err,res){
        if (err) throw err
        req.data = {}
        req.data.message = `Documents were modified.`
        next()
        
    })
}

export default func