nodejs操作 mongodb數(shù)據(jù)庫增刪改查
1.安裝mongodb
2.安裝nodejs
3.安裝mongoose模塊
創(chuàng)建node增刪改查執(zhí)行文件
添加數(shù)據(jù):insert.js
//引入mongoose模塊
var mongoose = require('mongoose');
//創(chuàng)建一個鏈接条辟,并選擇數(shù)據(jù)庫
var db = mongoose.createConnection('mongodb://localhost:27017/san_db');
//設置數(shù)據(jù)類型
var monSchema = new mongoose.Schema({
name:{type:String,default:'xiaosan'},
age:{type:Number,min:22,index:true},
sex:{type:String}
});
//選擇一個集合
var monmodel = db.model('users',monSchema);
//插入的數(shù)據(jù)
var content = {name:'三',age:25,sex:'男'};
//實例化一條記錄
var monInsert = new monmodel(content);
//執(zhí)行保存數(shù)據(jù)
monInsert.save(function(err){
if(err){
console.log(err);
}else{
console.log('save data is ok!');
}
//關閉數(shù)據(jù)庫
db.close();
})
查詢數(shù)據(jù):find.js
//引入mongoose模塊
var mongoose = require('mongoose');
//創(chuàng)建一個鏈接翁都,并選擇數(shù)據(jù)庫
var db = mongoose.createConnection('mongodb://localhost:27017/san_db');
//設置數(shù)據(jù)類型
var monSchema = new mongoose.Schema({
name:{type:String,default:'lihao'},
age:{type:Number,min:22,index:true},
sex:{type:String} });
//選擇一個集合
var monmodel = db.model('users',monSchema);
//查詢條件
var content = {name:'三'};
//1代表占位符
var field = {name:1,age:1,sex:1};
//執(zhí)行查詢
monmodel.find(content,field,function(err,result){
if(err){
console.log(err);
}else{
console.log(result);
}
//關閉數(shù)據(jù)庫
db.close();
})
修改數(shù)據(jù):update.js
//引入mongoose模塊
var mongoose = require('mongoose');
//創(chuàng)建一個鏈接烫止,并選擇數(shù)據(jù)庫
var db = mongoose.createConnection('mongodb://localhost:27017/san_db');
//設置數(shù)據(jù)類型
var monSchema = new mongoose.Schema({
name:{type:String,default:'lihao'},
age:{type:Number,min:22,index:true},
sex:{type:String} });
//選擇一個集合
var monmodel = db.model('users',monSchema);
//修改的條件
var content = {name:'三'};
//修改的內容
var newData = {set:{name:'小三'}};
//執(zhí)行更新
monmodel.update(content,newData,function(err){
if(err){
console.log(err);
}else{
console.log(update is ok!);
}
//關閉數(shù)據(jù)庫
db.close();
})
刪除數(shù)據(jù):remove.js
//引入mongoose模塊
var mongoose = require('mongoose');
//創(chuàng)建一個鏈接贱呐,并選擇數(shù)據(jù)庫
var db = mongoose.createConnection('mongodb://localhost:27017/san_db');
//設置數(shù)據(jù)類型
var monSchema = new mongoose.Schema({
name:{type:String,default:'lihao'},
age:{type:Number,min:22,index:true},
sex:{type:String} });
//選擇一個集合
var monmodel = db.model('users',monSchema);
//刪除的條件
var content = {name:'三'};
//執(zhí)行刪除數(shù)據(jù)
monmodel.remove(content,function(err){
if(err){
console.log(err);
}else{
console.log(remove is ok!);
}
//關閉數(shù)據(jù)庫
db.close();
})
有閃電