Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript MongoDB


May 09, 2021 CoffeeScript


Table of contents


Mongodb

Problem

You need an interface to connect to a MongoDB database.

Solution

For Node .js

Installation

Save the record

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

Find the record

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

For browsers

A REST-based interface In engineering, AJAX-based access channels are provided.

Discuss

This method separates save and find into separate instances, with the aim of distracting the focus of the connection tasks specified by MongoDB and recycling the tasks. The async module can help with such asynchronous calls.