CoffeeScript - MongoDB 数据库
MongoDB 是一个跨平台、面向文档的数据库,可提供高性能、高可用性和易于扩展的特性。 MongoDB 致力于集合和文档的概念。 如需更多信息,请阅读我们的 MongoDB 教程。
在本章中,您将学习如何使用 CoffeeScript 与 MongoDB 数据库进行通信。
安装
MongoDB 数据库可以使用 MongoDB 的 Node.js 2.0 驱动程序与 CoffeeScript 集成。 首先,您需要在您的系统中安装 MongoDB,参考我们 MongoDB 教程的Windows 平台安装 MongoDB环境章节。
成功安装 MongoDB 后浏览其 bin 文件夹(如果您尚未设置路径)并启动 MongoDB 服务,如下所示。
C:\Program Files\MongoDB\Server\3.2\bin> mongod
最后通过在命令提示符下执行以下 NPM 命令来安装 MongoDB 驱动程序及其依赖项。
npm install mongodb --save
连接到 MongoDB
为了连接到 MongoDB,首先使用它创建 MongoClient,调用 connect() 函数。 此函数接受 url 和回调函数作为参数。
下面的 CoffeeScript 代码展示了如何连接到 MongoDB 服务器。 如果 MongoDB 服务器正在您的系统中运行,则此程序会建立与服务器的连接。
#Requiring the Mongodb package
mongo = require 'mongodb'
#Creating a MongoClient object
MongoClient = mongo.MongoClient
#Preparing the URL
url = 'mongodb://localhost:27017/testdb'
#Connecting to the server
MongoClient.connect url, (err, db) ->
if err
console.log 'Unable to connect . Error:', err
else
console.log 'Connection established to', url
#Close connection
db.close()
return
将上述代码保存在名为 connect_db.coffee 的文件中,然后按如下所示执行。 如果成功创建数据库,那么它将给出以下消息
c:\> coffee connect_db.coffee coffee connect_db.collection Connection established to mongodb://localhost:27017/testdb
创建一个集合
MongoDB 中的集合包含我们存储在其中的文档。 您可以使用 collection() 函数创建集合。 此函数接受一个字符串参数,表示我们要创建的集合的名称。
下面的 CoffeeScript 代码展示了如何在 MongoDB 中创建一个集合。 如果出现任何错误,它们将显示在控制台上。
#Requiring the Mongodb package
mongo = require 'mongodb'
#Creating a MongoClient object
MongoClient = mongo.MongoClient
#Preparing the URL
url = 'mongodb://localhost:27017/testdb'
#Connecting to the server
MongoClient.connect url, (err, db) ->
if err
console.log 'Unable to connect . Error:', err
else
console.log 'Connection established to', url
#Create collection
col = db.collection('My_collection')
console.log "Collection created successfully."
#Close connection
db.close()
return
将上述代码保存在名为 create_collection.coffee 的文件中,然后按如下所示执行。 如果集合创建成功,那么它会给出以下信息
c:/> coffee create_collection.coffee Connection established to mongodb://localhost:27017/testdb Collection created successfully.
插入文档
您可以将文档插入到 MongoDB 中的集合中,您需要通过传递需要插入的文档列表作为参数来调用名为 insert() 的函数。
下面的 CoffeeScript 代码展示了如何将文档插入到名为 My_collection 的集合中。 如果出现任何错误,它们将显示在控制台上。
#Sample JSON Documents
doc1 = {name: 'Ram', age: 26, city: 'Hyderabad'}
doc2 = {name: 'Rahim', age: 27, city: 'Banglore'}
doc3 = {name: 'Robert', age: 28, city: 'Mumbai'}
#Requiring the Mongodb package
mongo = require 'mongodb'
#Creating a MongoClient object
MongoClient = mongo.MongoClient
#Preparing the URL
url = 'mongodb://localhost:27017/testdb'
#Connecting to the server
MongoClient.connect url, (err, db) ->
if err
console.log 'Unable to connect . Error:', err
else
console.log 'Connection established to', url
#Creating collection
col = db.collection('My_collection')
#Inserting documents
col.insert [doc1,doc2,doc3], (err, result) ->
if err
console.log err
else
console.log "Documents inserted successfully"
#Close connection
db.close()
return
return
将上述代码保存在名为 insert_documents.coffee 的文件中,然后按如下所示执行。 如果文件插入成功,则会显示以下消息
c:/> coffee insert_documents.coffee Connection established to mongodb://localhost:27017/testdb Documents inserted successfully
阅读文档
您可以使用名为 find() 的函数检索存储在 MongoDB 中的文档。 以下 CoffeeScript 代码显示了如何检索存储在 MongoDB 中的记录。
#Requiring the Mongodb package
mongo = require 'mongodb'
#Creating a MongoClient object
MongoClient = mongo.MongoClient
#Preparing the URL
url = 'mongodb://localhost:27017/testdb'
#Connecting to the server
MongoClient.connect url, (err, db) ->
if err
console.log 'Unable to connect . Error:', err
else
console.log 'Connection established to', url
#Creating collection object
col = db.collection('My_collection')
#Inserting Documents
col.find({name: 'Ram'}).toArray (err, result)->
if err
console.log err
else
console.log 'Found:', result
#Closing connection
db.close()
return
return
将上面的代码保存在名为 read_documents.coffee 的文件中,然后按如下所示执行它。 该程序在指定的集合中检索所需的文档并将其显示如下所示。
C:\> coffee read_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ { _id: 56e269c10478809c3009ad1e,
name: 'Ram',
age: 26,
city: 'Hyderabad' } ]
您还可以通过执行 find() 函数而不向其传递任何参数来读取特定集合中存在的所有文档,如下所示。
#Requiring the Mongodb package
mongo = require 'mongodb'
#Creating a MongoClient object
MongoClient = mongo.MongoClient
#Preparing the URL
url = 'mongodb://localhost:27017/testdb'
#Connecting to the server
MongoClient.connect url, (err, db) ->
if err
console.log 'Unable to connect . Error:', err
else
console.log 'Connection established to', url
#Creating collection object
col = db.collection('My_collection')
#Reading all Documents
col.find().toArray (err, result)->
if err
console.log err
else
console.log 'Found:', result
#Closing connection
db.close()
return
return
将上述代码保存在名为 read_all_documents.coffee 的文件中,然后按如下所示执行。 该程序检索指定集合中的所有文档并如下所示显示。
C:\> coffee read_all_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ { _id: 56e2c5e27e0bad741a68c03e,
name: 'Ram',
age: 26,
city: 'Hyderabad' },
{ _id: 56e2c5e27e0bad741a68c03f,
name: 'Rahim',
age: 27,
city: 'Banglore' },
{ _id: 56e2c5e27e0bad741a68c040,
name: 'Robert',
age: 28,
city: 'Mumbai' } ]
更新文档
您可以使用名为 update() 的函数更新存储在 MongoDB 中的文档。 下面的 CoffeeScript 代码展示了如何更新存储在 MongoDB 中的记录。
#Get mongo client object
MongoClient = require('mongodb').MongoClient
#Connecting to mongodb
url = 'mongodb://localhost:27017/testdb'
MongoClient.connect url, (err, db) ->
if err
console.log 'Unable to connect . Error:', err
else
console.log 'Connection established to', url
#Creating collection
col = db.collection('My_collection')
#Reading Data
col.update {name:'Ram'},{$set:{city:'Delhi'}},(err, result)->
if err
console.log err
else
console.log "Document updated"
#Closing connection
db.close()
return
return
该程序将名为 Ram 的员工所在的城市从海得拉巴更新为德里。
将上述代码保存在名为 update_documents.coffee 的文件中,然后按如下所示执行。 该程序检索指定集合中的文档并将其显示如下所示。
C:\> coffee update_documents.coffee Connection established to mongodb://localhost:27017/testdb Document updated
更新后,如果你执行read_documents.coffee程序,你会观察到名为Ram的人的城市名从Hyderabad更新为Delhi.
C:\> coffee Read_all_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ { _id: 56e2c5e27e0bad741a68c03e,
name: 'Ram',
age: 26,
city: 'Delhi' },
{ _id: 56e2c5e27e0bad741a68c03f,
name: 'Rahim',
age: 27,
city: 'Banglore' },
{ _id: 56e2c5e27e0bad741a68c040,
name: 'Robert',
age: 28,
city: 'Mumbai' } ]
删除文档
您可以使用 remove() 函数从集合中删除所有文档。 以下 CoffeeScript 代码显示了如何删除存储在 MongoDB 中的所有记录。
#Get mongo client object
MongoClient = require('mongodb').MongoClient
#Connecting to mongodb
url = 'mongodb://localhost:27017/testdb'
MongoClient.connect url, (err, db) ->
if err
console.log 'Unable to connect . Error:', err
else
console.log 'Connection established to', url
#Creating collection
col = db.collection('My_collection')
#Deleting Data
col.remove()
console.log "Document deleted"
#Closing connection
db.close()
return
将上述代码保存在名为 delete_documents.coffee 的文件中,然后按如下所示执行。 此程序删除指定集合中的所有文档并显示以下消息。
C:\> coffee delete_documents.coffee Connection established to mongodb://localhost:27017/testdb Document deleted
删除后,如果你执行read_documents.coffee程序,那么你会得到一个空集合,如下图。
C:\> coffee Read_all_documents.coffee Connection established to mongodb://localhost:27017/testdb Found: [ ]

