Coffeescript 简明教程
CoffeeScript - MongoDB
MongoDB是一个跨平台、面向文档的数据库,提供高性能、高可用性和易于扩展。MongoDB基于集合和文档的概念。有关更多信息,请阅读我们的 MongoDB Tutorial 。
MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document. For more information read our MongoDB Tutorial.
在本章中,您将学习如何使用CoffeeScript与MongoDB数据库通信。
In this chapter you will learn how to communicate with MongoDB database using CoffeeScript.
Installation
MongoDB数据库可以使用MongoDB的Node.js 2.0驱动与CoffeeScript集成。首先,您需要在系统中安装MongoDB,方法是参考我们的MongoDB教程的 environment 章节。
The MongoDB database can be integrated with CoffeeScript using Node.js 2.0 driver of MongoDB. First of all you need to install MongoDB in your system, by referring the environment chapter of our MongoDB tutorial.
在成功安装MongoDB后,浏览其 bin 文件夹(如果您没有设置路径),并按照如下所示启动MongoDB服务。
After installing MongoDB successfully browse through its bin folder (if you haven’t set the path) and start the MongoDB service as shown below.
C:\Program Files\MongoDB\Server\3.2\bin> mongod
最后,通过在命令提示符中执行以下NPM命令,安装MongoDB驱动程序及依赖项。
Finally install MongoDB driver and it’s dependencies by executing the following NPM command in the command prompt.
npm install mongodb --save
Connecting to MongoDB
为了连接到MongoDB,首先使用它创建MongoClient,调用 connect() 函数。此函数接受url和回调函数作为参数。
In order to connect to MongoDB, first of all create MongoClient using this, invoke the connect() function. This function accepts url, and a callback function as parameters.
以下CoffeeScript代码显示了如何连接到MongoDB服务器。如果MongoDB服务器在您的系统中正在运行,此程序将建立与服务器的连接。
Following CoffeeScript code shows how to connect to MongoDB server. If the MongoDB server is running in your system this program establishes a connection to the server.
#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 的文件中,然后按以下所示执行。如果数据库创建成功,将会显示以下消息
Save the above code in a file with name connect_db.coffee and execute it as shown below. If database is successfully created then it will give following message
c:\> coffee connect_db.coffee
coffee connect_db.collection
Connection established to mongodb://localhost:27017/testdb
Creating a Collection
MongoDB 中的集合容纳我们存储在其中的文档。可以使用 collection() 函数创建集合。该函数接受一个字符串参数,该参数表示我们要创建的集合的名称。
A collection in MongoDB holds the documents we store in it. You can create a collection by using the collection() function. This function accepts a string argument that represents the name of the collection we want to create.
以下 CoffeeScript 代码展示了如何在 MongoDB 中创建集合。如果有任何错误,它们都会在控制台上显示。
Following CoffeeScript code shows how to create a collection in MongoDB. In case of any errors, they will be displayed on the console.
#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 的文件中,然后按以下所示执行。如果集合创建成功,将会显示以下消息
Save the above code in a file with name create_collection.coffee and execute it as shown below. If the collection is created successfully then it will give following message
c:/> coffee create_collection.coffee
Connection established to mongodb://localhost:27017/testdb
Collection created successfully.
Inserting Documents
可以在 MongoDB 中向集合中插入文档,你需要调用名为 insert() 的函数,并按需传入要插入的文档列表,作为参数。
You can inset documents in to a collection in MongoDB you need to invoke a function named insert() by passing the list of documents that are needed to be inserted, as parameters.
以下 CoffeeScript 代码展示了如何将文档插入名为 My_collection 的集合中。如果有任何错误,将在控制台中显示。
Following CoffeeScript code shows how to insert documents in to a collection named My_collection. In case of any errors, they will be displayed on the console.
#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 的文件中,并按照以下方式执行它。如果文档插入成功,则会显示以下消息
Save the above code in a file with name insert_documents.coffee and execute it as shown below. If the documents are inserted successfully then it gives following message
c:/> coffee insert_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Documents inserted successfully
Reading Documents
可以使用名为 find() 的函数检索存储在 MongoDB 中的文档。以下 CoffeeScript 代码展示了如何检索存储在 MongoDB 中的记录。
You can retrieve the documents that are stored in MongoDB using a function named find(). The following CoffeeScript code shows how to retrieve the records that are stored in 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 的文件中,并按照以下方式执行它。此程序按指定集合检索所需的文档并按照以下方式显示它。
Save the above code in a file with name read_documents.coffee and execute it as shown below. This programs retrieves the required document in the specified collection and displays it as shown below.
C:\> coffee read_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ { _id: 56e269c10478809c3009ad1e,
name: 'Ram',
age: 26,
city: 'Hyderabad' } ]
你还可以通过按照以下方式执行 find() 函数来读取特定集合中存在的文档,而不向它传递任何参数。
You can also read all the documents existing in a particular collection by executing the find() function with out passing any arguments to it as shown below.
#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 的文件中,并按照以下方式执行它。此程序按指定集合检索所有文档并按照以下方式显示它。
Save the above code in a file with name read_all_documents.coffee and execute it as shown below. this programs retrieves all the documents in the specified collection and displays it as shown below.
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' } ]
Updating Documents
可以使用名为 update() 的函数更新存储在 MongoDB 中的文档。以下 CoffeeScript 代码展示了如何更新存储在 MongoDB 中的记录。
You can update the documents that are stored in MongoDB using a function named update(). Following CoffeeScript code shows how to update the records that are stored in 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 名为员工的城市从 Hyderabad 更新为 Delhi。
This program updates the city of the employee named Ram from Hyderabad to Delhi.
将上面的代码保存在名为 update_documents.coffee 的文件中,并按照以下方式执行它。此程序按指定集合检索文档并按照以下方式显示它。
Save the above code in a file with name update_documents.coffee and execute it as shown below. this programs retrieves the documents in the specified collection and displays it as shown below.
C:\> coffee update_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Document updated
更新后,如果你执行 read_documents.coffee 程序,则你会观察到名为 Ram 的人的城市名从 Hyderabad 更新为 Delhi 。
After updating, if you execute the read_documents.coffee program, then you will observe that the city name of the person named Ram is updated from Hyderabad to 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' } ]
Deleting Documents
可以使用 remove() 函数从集合中删除所有文档。以下 CoffeeScript 代码展示了如何删除存储在 MongoDB 中的所有记录。
You can delete all the documents from the collection using the remove() function. Following CoffeeScript code shows how to delete all the records that are stored in 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 的文件中,并按照以下方式执行它。此程序删除指定集合中的所有文档,显示以下消息。
Save the above code in a file with name delete_documents.coffee and execute it as shown below. this programs removes all the documents in the specified collection displaying the following messages.
C:\> coffee delete_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Document deleted
删除后,如果你执行 read_documents.coffee 程序,则你会看到一个空集合,如下所示。
After deleting, if you execute the read_documents.coffee program, then you will get an empty collection as shown below.
C:\> coffee Read_all_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ ]