https://mongoosejs.com/javascript
MongooseElegant 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 mongooseNow 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
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:
db.collection.insertOne()
New in version 3.2db.collection.insertMany()
New in version 3.2In 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.
click to enlargeFor examples, see:
Update Operations
Update operations modify existing documents in a collection. MongoDB provides the following methods to update documents of a collection:
db.collection.updateOne()
New in version 3.2db.collection.updateMany()
New in version 3.2db.collection.replaceOne()
New in version 3.2In 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:
db.collection.deleteOne()
New in version 3.2db.collection.deleteMany()
New in version 3.2In 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.
https://developer.mozilla.org/zh-CN/docs/Learn/Server-side/Express_Nodejs/mongoose
经过使用 SQL 或数据库支持的任何查询语言,均可以得到最佳性能。ODM一般比较慢,由于它们使用翻译代码,在对象和数据库格式之间进行映射,这可能不会使用最有效的数据库查询(尤为是若是ODM支持不一样的数据库后端,而且必须在各个数据库所支持的功能方面,作出更大的折衷)。
使用 ORM 的好处是,程序员能够继续用 JavaScript 对象而不是数据库语义来思考 — 若是您须要使用不一样数据库(在相同或不一样的网站上),那么尤为如此。他们还提供了一个明显的地方来执行数据验证和检查。
安装和使用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")
产生数据