课程表

CoffeeScript 语法

CoffeeScript 类和对象

CoffeeScript 字符串

CoffeeScript 数组

CoffeeScript 日期和时间

CoffeeScript 数学

CoffeeScript 方法

CoffeeScript 元编程

CoffeeScript jQuery

CoffeeScript 正则表达式

CoffeeScript 网络

CoffeeScript 设计模式

CoffeeScript 数据库

CoffeeScript 测试

工具箱
速查手册

CoffeeScript MongoDB

当前位置:免费教程 » JS/JS库/框架 » CoffeeScript

问题

你需要与一个 MongoDB 数据库连接的接口。

解决方案

对于 Node.js

安装

保存记录

  1. mongo = require 'mongodb'
  2. server = new mongo.Server "127.0.0.1", 27017, {}
  3. client = new mongo.Db 'test', server, {w:1}
  4. # save() updates existing records or inserts new ones as needed
  5. exampleSave = (dbErr, collection) ->
  6. console.log "Unable to access database: #{dbErr}" if dbErr
  7. collection.save { _id: "my_favorite_latte", flavor: "honeysuckle" }, (err, docs) ->
  8. console.log "Unable to save record: #{err}" if err
  9. client.close()
  10. client.open (err, database) ->
  11. client.collection 'coffeescript_example', exampleSave

查找记录

  1. mongo = require 'mongodb'
  2. server = new mongo.Server "127.0.0.1", 27017, {}
  3. client = new mongo.Db 'test', server, {w:1}
  4. exampleFind = (dbErr, collection) ->
  5. console.log "Unable to access database: #{dbErr}" if dbErr
  6. collection.find({ _id: "my_favorite_latte" }).nextObject (err, result) ->
  7. if err
  8. console.log "Unable to find record: #{err}"
  9. else
  10. console.log result # => { id: "my_favorite_latte", flavor: "honeysuckle" }
  11. client.close()
  12. client.open (err, database) ->
  13. client.collection 'coffeescript_example', exampleFind

对于浏览器

一个基于 REST 的接口在工程中,会提供基于 AJAX 的访问通道。

讨论

这个方法将 save 和 find 分开进单独的实例,其目的是分散 MongoDB 指定的连接任务的关注点以及回收任务。async 模块可以帮助这样的异步调用。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号