node.js 操作mongodb数据库
nodejs 自带组件 mongodb/mongoose
npm install mongodb --save()
npm init
mongoose增删改查操作
插入
var mongoose = require('mongoose'); var db = mongoose.createConnection('mongodb://192.168.127.131:27017/ab_db'); var monSchema = new mongoose.Schema({ name:{ type:String,default:'ab'}, age:{type:Number}, sex:{type:String} } }); var monModel = db.model('user',monSchema); var content = {name:'AQ',age:29,sex:'girl'}; var monInsert = new monMondel('content'); monInsert = new monModel("content"); monInsert.save(function(err){ if(err){ console.log(err); }else{ console.log('Insert Successed'); } db.close(); });
查询
var mongoose = require('mongoose');
var db mongoose.createConnection('mongodb://192.168.127.131:27017/ab_db');
var monSchema = new mongoose.Schema({
name:{type:String,default:'db'},
age:{type:Number},
sex:{type:String}
});
var monModel = db.model('user',monSchema);
//var content = {name:'CWQ',age:28,sex:'girl'};
var content = {name:'CDY'};
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();
});
修改
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://192.168.127.131:27017/ab_db');
var monSchema = new mongoose.Schema({
name:{type:String,default:'ab'},
age:{type:Number},
sex:{type:String}
});
var monModel = db.model('user',monSchema);
var content = {name:'zs'};
var gengxindata = {$set:{name:'zangsan',age:26}};
monModel.update(content,gengxindata,function(err,result){
if (err) {
console.log(err);
}else{
console.log(result);
}
db.close();
});
删除
var mongoose = require('mongoose');
var db=mongoose.createConnection('mongodb://192.168.127.131:27017/ab_db');
var monSchema = new mongoose.Schema({
name:{type:String,default:'ab'},
age:{type:Number},
sex:{type:String}
});
var monModel = db.model('user',monSchema);
var content = {name:'zs'};
monModel.remove(content,function(err,result){
if (err) {
console.log(err);
}else{
console.log(result);
}
db.close();
});
网友评论