Monk is used in nodejs to access mongodb

  • 2020-03-30 03:30:05
  • OfStack

Install the mongo

I feel or by mannual install on a little: (link: http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/)

Start the mongo


$ mongod

Connection mogodb


$ mongo

mongo> use monk-app

mongo> db.products.insert({"name":"apple juice", "description":"good"})

WriteResult({ "nInserted" : 1 })

mongo> db.products.find().pretty()

{
  "_id" : ObjectId("53b4cf8d5ef358e649ff1665"),
  "name" : "apple juce",
  "description" : "good"
}

Access mongodb from nodejs using monk


$ mkdir monk-app

$ cd monk-ap

Create package. Json


{
 "name": "monk-app",
 "version": "0.0.1",
 "private": true,
 "dependencies": {
  "mongodb": "*",
  "monk": "*"
 }
}


$ npm install

To create the app. Js

Link to the database you created earlier


var monk = require('monk')
var db = monk('localhost:27017/monk-demo')

Read data:


var monk = require('monk')
var db = monk('localhost:27017/monk-demo')

var products = db.get('products')
  products.find({}, function(err, docs) {
   console.log(docs)
})

[ { _id: 53b4d3238cb4707ca35ab6f8,
  name: 'apple juice',
  description: 'good' } ]

Insert data:


products.insert({"name":"orange juice","description":"just so so"})

Search data:


products.find({"name":"apple juice"}, function(err, docs) {
  console.log(docs)
})


Related articles: