目录

CoffeeScript - MongoDB( MongoDB)

MongoDB是一个跨平台,面向文档的数据库,提供高性能,高可用性和易扩展性。 MongoDB适用于集合和文档的概念。 有关更多信息,请阅读我们的MongoDB教程

在本章中,您将学习如何使用CoffeeScript与MongoDB数据库进行通信。

安装 (Installation)

可以使用MongoDB的Node.js 2.0驱动程序将MongoDB数据库与CoffeeScript集成。 首先,您需要通过参考MongoDB教程的environment章节在系统中安装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()的函数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()函数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: [ ]
↑回到顶部↑
WIKI教程 @2018