Mongoose

 

Mongoose

https://mongoosejs.com/javascript

Elegant MongoDB object modeling for Node.jshtml

 

Let's face it, writing MongoDB validation, casting and business logic boilerplate is a drag. That's why we wrote Mongoose.前端

const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); const Cat = mongoose.model('Cat', { name: String }); const kitty = new Cat({ name: 'Zildjian' }); kitty.save().then(() => console.log('meow')); 

Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.java

https://mongoosejs.com/docs/index.htmlnode

Next install Mongoose from the command line using npm:程序員

$ npm install mongoose

Now say we like fuzzy kittens and want to record every kitten we ever meet in MongoDB. The first thing we need to do is include mongoose in our project and open a connection to the test database on our locally running instance of MongoDB.web

// getting-started.js var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); 

We have a pending connection to the test database running on localhost. We now need to get notified if we connect successfully or if a connection error occurs:mongodb

var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { // we're connected! }); 

 

https://mongoosejs.com/docs/guides.html數據庫

指南express

Mongoose Core Concepts

 

Mongo API

https://docs.mongodb.com/manual/crud/

使用數據庫語言進行增刪改查,以下:

Create Operations

Create or insert operations add new documents to a collection. If the collection does not currently exist, insert operations will create the collection.

MongoDB provides the following methods to insert documents into a collection:

In MongoDB, insert operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.

The components of a MongoDB insertOne operations.

For examples, see Insert Documents.

Read Operations

Read operations retrieves documents from a collection; i.e. queries a collection for documents. MongoDB provides the following methods to read documents from a collection:

You can specify query filters or criteria that identify the documents to return.

For examples, see:

Update Operations

Update operations modify existing documents in a collection. MongoDB provides the following methods to update documents of a collection:

In MongoDB, update operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.

You can specify criteria, or filters, that identify the documents to update. These filters use the same syntax as read operations.

The components of a MongoDB updateMany operation.

For examples, see Update Documents.

Delete Operations

Delete operations remove documents from a collection. MongoDB provides the following methods to delete documents of a collection:

In MongoDB, delete operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.

You can specify criteria, or filters, that identify the documents to remove. These filters use the same syntax as read operations.

The components of a MongoDB deleteMany operation.

For examples, see Delete Documents.

 

ORM/ODM

https://developer.mozilla.org/zh-CN/docs/Learn/Server-side/Express_Nodejs/mongoose

經過使用 SQL 或數據庫支持的任何查詢語言,均可以得到最佳性能。ODM一般比較慢,由於它們使用翻譯代碼,在對象和數據庫格式之間進行映射,這可能不會使用最有效的數據庫查詢(尤爲是若是ODM支持不一樣的數據庫後端,而且必須在各個數據庫所支持的功能方面,作出更大的折衷)。

 

使用 ORM 的好處是,程序員能夠繼續用 JavaScript 對象而不是數據庫語義來思考 — 若是您須要使用不一樣數據庫(在相同或不一樣的網站上),那麼尤爲如此。他們還提供了一個明顯的地方來執行數據驗證和檢查。

Tip:使用ODM / ORM一般能夠下降開發和維護成本!除非您很是熟悉本地查詢語言,或者性能對您相當重要,不然您應該強烈考慮使用 ODM。

 

撰寫本文時,受歡迎的幾種解決方案是:

  • Mongoose: Mongoose是一個MongoDB對象建模工具,用於在異步環境中工做。
  • Waterline: 它是從基於Express的 Sails web 框架中提取的 ORM。它提供了一個統一的 API,來訪問衆多不一樣的數據庫,包括Redis,mySQL,LDAP,MongoDB 和 Postgres。

 

安裝和使用mongodb 和 mongoose 也參考本文:

https://developer.mozilla.org/zh-CN/docs/Learn/Server-side/Express_Nodejs/mongoose

定義模型

// Define schema
var Schema = mongoose.Schema;

var SomeModelSchema = new Schema({
    a_string: String,
    a_date: Date
});

// Compile model from schema
var SomeModel = mongoose.model('SomeModel', SomeModelSchema );

生成實例,並保存

// Create an instance of model SomeModel
var awesome_instance = new SomeModel({ name: 'awesome' });

// Save the new model instance, passing a callback
awesome_instance.save(function (err) {
  if (err) return handleError(err);
  // saved!
});

 

快速入門參考:

http://www.cnblogs.com/zhongweiv/p/mongoose.html

 

本身動手

 

db.js

var mongoose = require('mongoose'),
    DB_URL = 'mongodb://localhost:27017/zhipin';

/**
 * 鏈接
 */
mongoose.connect(DB_URL);

// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;

/**
  * 鏈接成功
  */
mongoose.connection.on('connected', function () {    
    console.log('Mongoose connection open to ' + DB_URL);  
});    

/**
 * 鏈接異常
 */
mongoose.connection.on('error',function (err) {    
    console.log('Mongoose connection error: ' + err);  
});    
 
/**
 * 鏈接斷開
 */
mongoose.connection.on('disconnected', function () {    
    console.log('Mongoose connection disconnected');  
});    

module.exports = mongoose;

 

summary.js

/**
 * 用戶信息
 */
var mongoose = require('./db'),
    Schema = mongoose.Schema;

var SummarySchema = new Schema({          
    Technology : { type: String },                    // 技術名稱
    Count : { type: Number },                        // 技術數目
});

module.exports = mongoose.model('summary',SummarySchema);

 

websocket調用數據保存,並替換靜態數據,推送前端:

var _ = require('lodash')

var express = require('express')

var app = express()

var server = app.listen(8081)

//websocket
var io = require('socket.io')(server);

var summary = require("./data_access/summary.js");

new summary({
    Technology: 'Hadoop',
    Count: 9,
}).save(function(err) {
    if (err) {
        console.log('保存失敗')
        return;
    }
    console.log('保存成功');
})


new summary({
    Technology: 'Spark',
    Count: 15,
}).save(function(err) {
    if (err) {
        console.log('保存失敗')
        return;
    }
    console.log('保存成功');
})


new summary({
    Technology: 'Storm',
    Count: 3,
}).save(function(err) {
    if (err) {
        console.log('保存失敗')
        return;
    }
    console.log('保存成功');
})



io.on('connection', function (socket) {
  socket.on('message', function (message) {
    console.log("message from client = "+message)
  })

  setInterval(function(){
    console.log("now sending chartData!")

    summary.find().exec(function (err, res) {
      console.log("Error:" + err)
        if (err) {
            console.log("Error:" + err);
        }
        else {
            console.log("Res:" + res);

            var chartData = {
                "columns": ["Technology", "Count"],
                "rows": [
                    /*
                    { "Technology": "Hadoop", "Count": 9 },
                    { "Technology": "Spark", "Count": 15 },
                    { "Technology": "Storm", "Count": 3 }
                    */
                ]
            }

            chartData.rows = res

            var ran_index = _.random(0, res.length-1);
            var ran_increment = _.random(500, 1000);

            chartData.rows.forEach( (item, index) => {
                if(index == ran_index){
                    item.Count += ran_increment
                    return true
                }
            })

            io.emit("chartData", JSON.stringify(chartData))
        }
    })
  }, 1000)

  socket.on('disconnect', function () {
    console.log("disconnected")
  })
})

console.log("websocket server init OK! on http://localhost:8081")

 

產生數據

相關文章
相關標籤/搜索