安装
npm install mongod
npm install mongoose
# 链接数据库
>```
var mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/dbname');
定义数据模型
var BlogPost = new Schema({
author : ObjectId,
title : String,
body : String,
date : Date
});
# 增删改查 demo
>```
//insert
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://192.168.127.132:27017/caideyang_db');
var monSchema = new mongoose.Schema({
name:{type:String,default:'Caideyang'},
age:{type:Number},
sex:{type:String}
});
var monModel = db.model('user',monSchema);
var content = {name:'zzd',age:16,sex:'A'};
var monInsert = new monModel(content);
monInsert.save(function(err){
if (err) {
console.log(err);
}else{
console.log('Insert Successed !');
}
db.close();
});
//find
var mongoose = require('mongoose');//引入模块
var db = mongoose.createConnection('mongodb://192.168.127.132:27017/caideyang_db');//创建连接,选择数据
var monSchema = new mongoose.Schema({ //设置一个基础的数据类型
name:{type:String,default:'Caideyang'},
age:{type:Number},
sex:{type:String}
});
var monModel = db.model('user',monSchema); //创建一个数据库集合(表)user,系统默认会加s
//var content = {name:'zdd',age:28,sex:'girl'}; //插入的内容
var content = {name:'zcc'};//定义查询条件
var field = {name:1,age:1,sex:1};//定义查询的字段
//var monInsert = new monModel(content);//设置内容
monModel.find(content,field,function(err,result){//数据插入操作
if (err) {
console.log(err);
}else{
console.log(result);
}
db.close();
});
//update
var mongoose = require('mongoose');//引入模块
var db = mongoose.createConnection('mongodb://192.168.127.132:27017/caideyang_db');//创建连接,选择数据
var monSchema = new mongoose.Schema({ //设置一个基础的数据类型
name:{type:String,default:'Caideyang'},
age:{type:Number},
sex:{type:String}
});
var monModel = db.model('user',monSchema); //创建一个数据库集合(表)user,系统默认会加s
//var content = {name:'zsc',age:10,sex:'girl'}; //插入的内容
var content = {name:'snc'};//定义查询条件
var gengxindata = {$set:{name:'程万清',age:26}}; //修改后的内容
//var field = {name:1,age:1,sex:1};//定义查询的字段
//var monInsert = new monModel(content);//设置内容
monModel.update(content,gengxindata,function(err,result){//数据更新操作
if (err) {
console.log(err);
}else{
console.log(result);
}
db.close();
});
//delete
var mongoose = require('mongoose');//引入模块
var db = mongoose.createConnection('mongodb://192.168.127.132:27017/caideyang_db');//创建连接,选择数据
var monSchema = new mongoose.Schema({ //设置一个基础的数据类型
name:{type:String,default:'Caideyang'},
age:{type:Number},
sex:{type:String}
});
var monModel = db.model('user',monSchema); //创建一个数据库集合(表)user,系统默认会加s
//var content = {name:'daa',age:10,sex:'girl'}; //插入的内容
var content = {name:'cac'};//定义删除条件
//var field = {name:1,age:1,sex:1};//定义查询的字段
//var monInsert = new monModel(content);//设置内容
monModel.remove(content,function(err,result){//数据删除操作
if (err) {
console.log(err);
}else{
console.log(result);
}
db.close();
});