我爱编程

mongodb组件mongoose的操作

2016-08-16  本文已影响0人  小苏008

1、mongodb插入操作

var = var mongoose=require('mongoose');

var db=mongoose.createConnection('mongodb://192.168.152.131:27017/test');

var monSchema=new mongoose.Schema({

name:{type:String,default:'cao'},

age:{type:Number},

sex:{type:String}

});

var monModel=db.model('user',monSchema);

var content={name:"xiami",age:18,sex:'女'};

var monInsert=new monModel(content);

monInsert.save(function(err){

if(err){

console.log(err);

}else{

console.log('写入数据成功');

}

db.close();

});

2、mongodb查找操作

var mongoose=require('mongoose');

var db=mongoose.createConnection('mongodb://192.168.152.131:27017/test');

var monSchema=new mongoose.Schema({

name:{type:String,default:'cao'},

age:{type:Number},

sex:{type:String}

});

var monModel=db.model('user',monSchema);

var content={};

var field={name:"xiami"};

monModel.find(content,field,function(err,result){

if(err){

console.log(err);

}else{

console.log(result);

}

db.close();

});

3、mongodb更新操作

var mongoose=require('mongoose');

var db=mongoose.createConnection('mongodb://192.168.152.131:27017/test');

var monSchema=new mongoose.Schema({

name:{type:String,default:'cao'},

age:{type:Number},

sex:{type:String}

});

var monModel=db.model('user',monSchema);

var info={name:"xiami"};

var update_data={$set:{name:''}};

monModel.update(info,update_data,function(err){

if(err){

console.log(err);

}else{

console.log("update completed");

}

db.close();

});

4、mongodb删除操作

var mongoose=require('mongoose');

var db=mongoose.createConnection('mongodb://192.168.152.131:27017/test');\

var monSchema=new mongoose.Schema({

name:{type:String,default:'cao'},

age:{type:Number},

sex:{type:String}

});

var monMode=db.model('user',monSschema);

var info={name:'xiami'};

var monInsert=new monModel(content);

monModel.remove(info,function(err)){

if(err){

console.log(err);

}else{

console.log('delete ok');

}

db.close();

});

console.log(db);

上一篇下一篇

猜你喜欢

热点阅读