使用MongoDB的ORM版Mongose来写你的数据操作吧!
来源:互联网 发布:手机淘宝上怎样卖东西 编辑:程序博客网 时间:2024/05/08 15:47
Adding the MongoDB Backend
The first necessary change is to add a connection to the MongoDB database. It’s added
to the primary app.js file, so the connection persists for the life of the application.
First, Mongoose is included into the file:
var mongoose = require('mongoose');
Implementing a Widget Model with Mongoose | 223
Then the database connection is made:
// MongoDB
mongoose.connect('mongodb://127.0.0.1/WidgetDB');
mongoose.connection.on('open', function() {
console.log('Connected to Mongoose');
});
Notice the URI for the MongoDB. The specific database is passed as the last part of the
URI.
This change and the aforementioned change converting routes to main are all the
changes necessary for app.js.
简单的意思就是说,在你的入口app.js哪里加多下面几行,
这样mongoose就会帮你连接好,后面的所有的操作都不需要再连接了,直接调用结构就好了。
如果你重复连接,就会报警啦!
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/WidgetDB');
mongoose.connection.on('open', function() {
console.log('Connected to Mongoose');
});
连接好后,我们新建一个 user.js文件,用来存放这个bean(Entity,或者schema也行,随你理解这个类吧)。
var mongoose = require('mongoose');var Schema = mongoose.Schema , ObjectId = Schema.ObjectId;var User = new Schema({ _id: {type: Number, require: true, trim: true, unique: true}, email: {type: String, required: true, trim: true}, pswd: {type: String, required: true, trim: true}});module.exports = mongoose.model('User', User);
var UserBean = require('./Schema/User'); var user = new UserBean(); user._id=121; user.email=email; user.pswd=password; console.log("start to find"); // //注册新用户 user.save(function (err, data) { if (err) { console.log("save error="+err); } else { console.log(data); } });
ok,是不是很简洁的样子?赶紧在你的项目中用这个吧
详细的介绍,还是看下官方文档吧!:
http://mongoosejs.com/
https://github.com/Automattic/mongoose
其余的nodejs的orm还有
sequelize
https://github.com/sequelize/sequelize
http://sequelizejs.com/
ORM2
https://www.npmjs.com/package/orm
- 使用MongoDB的ORM版Mongose来写你的数据操作吧!
- 使用VB.Net写一个简单的数据访问层(不能称ORM):CRUD操作
- mongose数据库权限的设置
- 使用mongodb的findAndModify命令来进行数据同步
- 使用VB.Net写一个简单的数据访问层(不能称ORM):前言
- 使用mongodb的orm映射框架Morphia的一些例子
- Mongodb 的ORM框架 Morphia 之 使用Morphia(映射对象)
- Mongodb 的ORM框架 Morphia 之 使用Morphia(映射对象) .
- Mongodb 的ORM框架 Morphia 之 使用Morphia(映射对象)
- 在Python中使用ORM(MongoEngine)控制MongoDB的方法
- MongoDB C++ 数组的写操作
- MongoDB C++ 数组的写操作
- 自己动手写ORM的感受
- greenDao的使用---重点来啦 实现ORM连表 增删改查 颤抖吧凡人
- 使用mongodb的js来统计数据
- 数据层新思路,写数据库无关的数据层 ORM在数据库内做更为合适
- orm Lite的使用
- ORM的使用
- 《JAVA编程思想》笔记-初始化与清理
- 第四周 项目一:体验常成员函数
- C++学习之数组
- mysql命令学习相关
- Plus One--LeetCode
- 使用MongoDB的ORM版Mongose来写你的数据操作吧!
- 2000年清华大学计算机研究生机试真题
- 教你如何使用搜索引擎批量检测网站注入点
- head 详解
- [LeetCode] Binary Tree Postorder Traversal
- Google: RateLimit
- C++中二维数组作为函数参数
- hadoop-2.6.0单机配置和伪分布式配置
- 我的Android入门之路:一、初步接触之GreenDAO学习使用体验