CoffeeScript MongoDB

2022-06-29 17:16 更新

MongoDB

問(wèn)題

你需要與一個(gè)MongoDB數(shù)據(jù)庫(kù)連接的接口。

解決方案

對(duì)于 Node.js

安裝

保存記錄

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

對(duì)于瀏覽器

一個(gè)基于 REST 的接口在工程中,會(huì)提供基于AJAX的訪問(wèn)通道。

討論

這個(gè)方法將save和find分開進(jìn)單獨(dú)的實(shí)例,其目的是分散MongoDB指定的連接任務(wù)的關(guān)注點(diǎn)以及回收任務(wù)。async 模塊可以幫助這樣的異步調(diào)用。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)