var mongoose = require('mongoose'),
DB_URL = 'mongodb://192.168.5.128:27017/mongoosesample';
/**
* 建立连接
*/
function mongoConnection() {
return mongoose.connect(DB_URL).connection;
}
/**
* 判断连接状态
*/
mongoConnection()
.on('error',function(err){
console.log('Mongoose connection error: ' + err);
})
.on('disconnected',function () {
console.log('Mongoose connection disconnected');
})
.on('connected',function () {
console.log('Mongoose connection open to ' + DB_URL);
});
如果需要改变mongodb的绑定URL,则修改mongodb配置文件 /etc/mongodb.conf
加上:bind_ip:192.168.5.128
连接的DB_URL,如果是本地就改为:
'mongodb://localhost:27017/mongoosesample';
------------------------------------------------------------------
连接到Mongodb之后,插入数据:
把下面的代码保存为:mongoTest.js
var mongoose = require('mongoose'),
DB_URL = 'mongodb://192.168.5.128:27017/mongoosesample';
module.exports= {
mongoConn:mongoConnection(),
schemaModule:schema_module()
};
/**
* 建立连接
*/
function mongoConnection() {
return mongoose.connect(DB_URL).connection;
}
/**
* 判断连接状态
*/
mongoConnection()
.on('error',function(err){
console.log('Mongoose connection error: ' + err);
})
.on('disconnected',function () {
console.log('Mongoose connection disconnected');
})
.on('connected',function () {
console.log('Mongoose connection open to ' + DB_URL);
});
/**
* 创建module
*/
function schema_module() {
var Schema = mongoose.Schema;
//声明Schema
var nodeSchema = new Schema({
name: String,
email: String
});
//构建model
return mongoose.model('Info', nodeSchema);
}
然后新建一个test.js
let mongoTest = require('./mongoTest')
mongoTest.mongoConn
mongoTest.schemaModule.create({'name':"zhang","email":"zhang@163.com"},function(err){
if(err){
console.log(err);
}else{
console.log('The new node is saved');
}
});
执行test.js就可以把
{'name':"zhang","email":"zhang@163.com"}
插入到infos这个文档中。
------------------------------------------------------------------------------
查询数据:
在test.js中加入查询数据的代码
let mongoTest = require('./mongoTest')
mongoTest.mongoConn
mongoTest.schemaModule1.create({'name':"liu","email":"mmm"},function(err){
if(err){
console.log(err);
}else{
console.log('The new node to info is saved');
}
});
mongoTest.schemaModule2.create({'t1':"t11","t2":"t22","t3":"t33"},function(err){
if(err){
console.log(err);
}else{
console.log('The new node to table is saved');
}
});
let query = mongoTest.schemaModule1.find({});
query.find({name: "liu"});
//或:query.where({name: "liu"})
query.exec(function (err, data) {
if (err) console.log(err);
else{ console.log(data)}
});
let query = mongoTest.schemaModule1.find({});
不加查询条件,则返回的是整 个文档。
-----------------------------------------------------
删除
mongoTest.schemaModule1.remove({});