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,是不是很简洁的样子?赶紧在你的项目中用这个吧
详细的介绍,还是看下官方文档吧!:
https://github.com/Automattic/mongoose
其余的nodejs的orm还有
sequelize
https://github.com/sequelize/sequelize
ORM2
https://www.npmjs.com/package/orm