码迷,mamicode.com
首页 > 其他好文 > 详细

Mongoose

时间:2018-08-24 02:00:56      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:工具   失败   ast   oca   生成   record   util   return   cat   

 

Mongoose

https://mongoosejs.com/

Elegant MongoDB object modeling for Node.js

 

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.

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

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.

// 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:

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

指南

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.

技术分享图片

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.

技术分享图片

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.

技术分享图片

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")

 

产生数据

技术分享图片

 

 

 

Mongoose

标签:工具   失败   ast   oca   生成   record   util   return   cat   

原文地址:https://www.cnblogs.com/lightsong/p/9527439.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!