用Node.js通过一个简单的示例访问MongoDB
我们修改了下一页的示例。
假设可以使用用户名scott和密码tiger123来访问MongoDB。
数据插入
#! /usr/bin/node
//
// mongodb_insert.js
//
// May/03/2020
// ----------------------------------------------------------------
console.log ("*** 開始 ***")
const host = 'scott:tiger123@localhost'
const port = 27017
const MongoClient = require('mongodb').MongoClient
const assert = require('assert')
const url = 'mongodb://' + host + ':' + port
// Database Name
const dbName = 'myproject'
const client = new MongoClient(url,
{useNewUrlParser: true,useUnifiedTopology: true})
client.connect(function(err) {
assert.equal(null, err)
console.log("Connected successfully to server")
const db = client.db(dbName)
insertDocuments(db, function() {
client.close()
console.log ("*** 終了 ***")
})
})
// ----------------------------------------------------------------
const insertDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents')
// Insert some documents
collection.insertMany([
{aa : 10}, {bb : 20}, {cc : 30}, {dd : 40}
], function(err, result) {
assert.equal(err, null)
assert.equal(4, result.result.n)
assert.equal(4, result.ops.length)
console.log("Inserted 4 documents into the collection")
callback(result)
})
}
// ----------------------------------------------------------------
执行结果
$ export NODE_PATH=/usr/lib/node_modules
$ ./mongodb_insert.js
*** 開始 ***
Connected successfully to server
Inserted 4 documents into the collection
*** 終了 ***
阅读数据
#! /usr/bin/node
//
// mongodb_read.js
//
// May/03/2020
// ----------------------------------------------------------------
console.log ("*** 開始 ***")
const host = 'scott:tiger123@localhost'
const port = 27017
const MongoClient = require('mongodb').MongoClient
const assert = require('assert')
const url = 'mongodb://' + host + ':' + port
const dbName = 'myproject'
const client = new MongoClient(url,
{useNewUrlParser: true,useUnifiedTopology: true})
client.connect(function(err) {
assert.equal(null, err)
console.log("Connected correctly to server")
const db = client.db(dbName)
findDocuments(db, function() {
client.close()
console.log ("*** 終了 ***")
})
})
// ----------------------------------------------------------------
const findDocuments = function(db, callback) {
const collection = db.collection('documents')
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null)
console.log("Found the following records")
console.log(docs)
callback(docs)
})
}
// ----------------------------------------------------------------
执行结果
$ export NODE_PATH=/usr/lib/node_modules
$ ./mongodb_read.js
*** 開始 ***
Connected correctly to server
Found the following records
[
{ _id: 5eafbfd5a6a9fb12219e7f50, aa: 10 },
{ _id: 5eafbfd5a6a9fb12219e7f51, bb: 20 },
{ _id: 5eafbfd5a6a9fb12219e7f52, cc: 30 },
{ _id: 5eafbfd5a6a9fb12219e7f53, dd: 40 }
]
*** 終了 ***