首頁 >web前端 >js教程 >nodejs中使用monk存取mongodb_node.js

nodejs中使用monk存取mongodb_node.js

WBOY
WBOY原創
2016-05-16 16:42:321759瀏覽

安裝mongodb

我覺得還是用mannual install可靠一點兒:http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/

啟動mongodb

$ mongod

連接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"
}

在nodejs中用monk存取mongodb

$ mkdir monk-app

$ cd monk-ap

建立package.json

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

$ npm install

建立app.js

連結前面建立的資料庫

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

讀取資料:

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' } ]

插入資料:

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

找出數據:

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn