你需要與一個(gè) MongoDB 數(shù)據(jù)庫(kù)連接的接口。
如果你的計(jì)算機(jī)中還沒(méi)有 MongoDB ,需要安裝。
mongo = require 'mongodb'
server = new mongo.Server "127.0.0.1", 27017, {}
client = new mongo.Db 'test', server, {w:1}
# save() updates existing records or inserts new ones as needed
exampleSave = (dbErr, collection) ->
console.log "Unable to access database: #{dbErr}" if dbErr
collection.save { _id: "my_favorite_latte", flavor: "honeysuckle" }, (err, docs) ->
console.log "Unable to save record: #{err}" if err
client.close()
client.open (err, database) ->
client.collection 'coffeescript_example', exampleSave
mongo = require 'mongodb'
server = new mongo.Server "127.0.0.1", 27017, {}
client = new mongo.Db 'test', server, {w:1}
exampleFind = (dbErr, collection) ->
console.log "Unable to access database: #{dbErr}" if dbErr
collection.find({ _id: "my_favorite_latte" }).nextObject (err, result) ->
if err
console.log "Unable to find record: #{err}"
else
console.log result # => { id: "my_favorite_latte", flavor: "honeysuckle" }
client.close()
client.open (err, database) ->
client.collection 'coffeescript_example', exampleFind
一個(gè)基于 REST 的接口在工程中,會(huì)提供基于 AJAX 的訪問(wèn)通道。
這個(gè)方法將 save 和 find 分開(kāi)進(jìn)單獨(dú)的實(shí)例,其目的是分散 MongoDB 指定的連接任務(wù)的關(guān)注點(diǎn)以及回收任務(wù)。async 模塊可以幫助這樣的異步調(diào)用。