បន្ទាប់ពីយើងបានសិក្សារបៀបតំឡើង mongodb នៅក្នុងកុំព្យូទ័ររួចហើយ យើងមកសិក្សាអំពី connect mongodb ជាមួយ node js
សូមចូលទៅមើល document របស់វាតាមវែបសាយ mongodb.com/docs/drivers

បង្កើត project ដោយតំឡើង package
- npm init -npm i mongodb

យើង copy code ពី mongodb docs ទៅដាក់នៅក្នុង app.js របស់យើង

បន្ទាប់មកយើង custom code ខ្លះ
const dbName = 'myProject'; យើងប្តូរទៅតាមឈ្មោះ database របស់យើង ។ ខ្ញុំសុំដាក់ថា peopleDB (const dbNam = 'peopleDB'
យើង run project ថាវា connect mongod បានជោគជ័យដែរឬទេ ។ ដោយចុច node app.js

នេះវាបានដំណើរការ connection បានជោគជ័យហើយ
Insert Document
នៅកន្លែងនេះ document យើងឈ្មោះ collections នៃ databass របស់យើង const collection = db.collection('documents');
នេះកូដសម្រាបបញ្ចូល
const insertResult = await collection.insertMany([ { "name": "Ros Dul", "country":"Cambodia"}, { "name": "Koko","country": "Taiwan" }, { "name": "Mey Mey", "country":"China" }]); console.log('Inserted documents =>', insertResult);
នេះកូដពេញ
const { MongoClient } = require('mongodb'); // Connection URL const url = 'mongodb://localhost:27017'; const client = new MongoClient(url); // Database Name const dbName = 'peopleDB'; async function main() { // Use connect method to connect to the server await client.connect(); console.log('Connected successfully to server'); const db = client.db(dbName); const collection = db.collection('people'); // the following code examples can be pasted here... // Insert document const insertResult = await collection.insertMany([ { "name": "Ros Dul", "country":"Cambodia"}, { "name": "Koko","country": "Taiwan" }, { "name": "Mey Mey", "country":"China" }]); console.log('Inserted documents =>', insertResult); return 'done.'; } main() .then(console.log) .catch(console.error) .finally(() => client.close());

Query document
// Query Document const findResult = await collection.find({}).toArray() console.log(findResult)
កូដពេញ
const { MongoClient } = require('mongodb'); // Connection URL const url = 'mongodb://localhost:27017'; const client = new MongoClient(url); // Database Name const dbName = 'peopleDB'; async function main() { // Use connect method to connect to the server await client.connect(); console.log('Connected successfully to server'); const db = client.db(dbName); const collection = db.collection('people'); // the following code examples can be pasted here... // Query Document const findResult = await collection.find({}).toArray() console.log(findResult) return 'done.'; } main() .then(console.log) .catch(console.error) .finally(() => client.close());

0 Comments