使用MongoDB的ORM版Mongose来写你的数据操作吧!

 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');

// MongoDB
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);


然后我们在 userModel.js里面调用他的话,就像下面这样 

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
mongodb-orm简介Mongodb ORM是基于java的ORM框架,简化了SDK的使用,使代码变得更清晰、简单。 与Ibatis类似,将查询、执行语句封装在xml中,与代码隔离。简称MQL。 项目中使用加入mongodb orm的支持包1. 添加jar包或maven支持<dependency>     <groupId>com.mongodborm</groupId>     <artifactId>mongodb-orm</artifactId>     <version>0.0.1-RELEASE</version> </dependency>2. 初始化mongodb templet        spring中初始化<bean id="mongoTemplet" class="com.mongodb.client.MongoClientTemplet">     <property name="factory">         <bean class="com.mongodb.client.MongoORMFactoryBean">             <property name="dataSource">                 <bean class="com.mongodb.client.MongoDataSource">                     <property name="nodeList" value="127.0.0.1:27017" />                     <property name="dbName" value="your db name" />                     <property name="userName" value="user name" />                     <property name="passWord" value="password" /> <!-- 可使用默认值 --> <property name="connectionsPerHost" value="" />                     <property name="threadsAllowedToBlock" value="" />                     <property name="connectionTimeOut" value="" />                     <property name="maxRetryTime" value="" />                     <property name="socketTimeOut" value="" />                 </bean>             </property>             <property name="configLocations">                 <list>                     <value>classpath:mql/mongo-mql.xml</value>                 </list>             </property>         </bean>     </property> </bean>        代码初始化    try {       Resource resource =  new ClassPathResource("mongo-mql.xml");           MongoORMFactoryBean factory = new MongoORMFactoryBean();       factory.setConfigLocations(new Resource[]{resource});       factory.init();          MongoClientTemplet templet = new MongoClientTemplet();       templet.setFactory(factory);       templet.init();     } catch(Exception e) {       e.printStackTrace();     }编MQLMapping<mapping id="model" class="test.mongodborm.Model">         <property column="_id" name="id" />         <property column="name" name="name" />         <property column="time" name="time" value="0" />         <property column="status" name="status" /> </mapping> <mapping id="extendModel" class="test.mongodborm.Model" extends="model">     <property column="newProperty" name="newProperty" /> </mapping>  select<select id="queryModelList" collection="test_sample">     <query class="java.lang.String">         <property column="name" name="${value}" />     </query>     <field mapping="model" />     <order>         <property column="time" value="desc" />     </order> </select> update/findAndModify<update id="updateModel" collection="test_sample">     <query class="test.mongodborm.Model$Child">         <property column="name" name="name" ignoreNull="true" />         <property column="time" operate="gte" value="0" type="number" />         <property column="status" operate="in">             <list type="number">0,1</list>         </property>     </query>     <action class="java.util.Map">         <property column="name" name="name" operate="set" />         <property column="status" operate="set" />     </action> </update>有嵌套的查询<select id="queryModelList3" collection="test_sample">     <query class="java.lang.String">         <property column="_id" value="${value}" />         <property column="time" value="0" type="number" />     </query>     <field class="java.util.Map">         <property column="name" name="name" />         <property column="parent" name="parent">             <value class="test.mongodborm.Model$Parent">                 <property column="name" name="name" />                 <property column="child" name="child">                     <value class="test.mongodborm.Model$Child">                         <property column="name" name="name" />                         <property column="time" name="time" value="0" />                     </value>                 </property>                 <property column="data" name="data">                     <value class="java.util.Map">                         <property column="title" name="title" />                         <property column="content" name="content" />                     </value>                 </property>             </value>         </property>         <property column="data" name="data">             <value class="java.util.Map">                 <property column="title" name="title" />                 <property column="content" name="content" />             </value>         </property>     </field>     <order class="java.util.Map">         <property column="time" name="time" value="desc" />     </order> </select>Templet用法Model model = mongoTemplet.findOne("queryModelList", "yuxiangping"); List<Model> list = mongoTemplet.findOne("queryModelList", ""); Model model = new Model(); model.setTime(1L); Map<String, String> action = new HashMap<String, String>(); action.put("name", "yuxiangping-update"); int update = mongoT emplet.update("updateModel", model, action);        更多的使用方法参见 sample.xml 标签:Mongodb
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值