使用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
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值