nodejs 操作 mongodb 數(shù)據(jù)庫(kù)
- 新建文件夾
- npm install mongodb
- npm install mongoose
- 編寫(xiě)鏈接文件 app.js
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://192.168.25.128:27017/fth');
console.log(db);
啟動(dòng)數(shù)據(jù)庫(kù) 啟動(dòng)app.js
編寫(xiě)model(插入數(shù)據(jù))
//包含依賴庫(kù)
var mongoose = require('mongoose');
//鏈接數(shù)據(jù)庫(kù)
var db = mongoose.createConnection('mongodb://192.168.25.128:27017/fth');
//設(shè)置基礎(chǔ)的數(shù)據(jù)類型
var monSchema = new mongoose.Schema({
name:{type:String,default:'fengtianhe'},
age:{type:Number},
sex:{type:String}
});
//選擇數(shù)據(jù)庫(kù)的集合(mongodb默認(rèn)加個(gè)s)
var monModel = db.model('user',monSchema);
//設(shè)置內(nèi)容
var content = {name:"馮天鶴",age:"18",sex:'男'};
//實(shí)例化插入類
var monInsert = new monModel(content);
//執(zhí)行插入方法
monInsert.save(function(err){
if(err){
console.log(err);
}else{
console.log('success');
}
db.close();
});-
執(zhí)行并查看數(shù)據(jù)庫(kù)
-
查詢功能
//包含依賴庫(kù) var mongoose = require('mongoose'); //鏈接數(shù)據(jù)庫(kù) var db = mongoose.createConnection('mongodb://192.168.25.128:27017/fth'); //設(shè)置基礎(chǔ)的數(shù)據(jù)類型 var monSchema = new mongoose.Schema({ name:{type:String,default:'fengtianhe'}, age:{type:Number}, sex:{type:String} }); //選擇數(shù)據(jù)庫(kù)的集合(mongodb默認(rèn)加個(gè)s) var monModel = db.model('user',monSchema); //設(shè)置搜索的條件 var content = {name:'fth'}; //設(shè)置要顯示的字段 var field = {name:1,age:1,sex:1}; monModel.find(content,field,function(err,result){ if(err){ console.log(err); }else{ console.log(result); } db.close(); });
-
執(zhí)行并查看結(jié)果
編寫(xiě)修改程序
//包含依賴庫(kù)
var mongoose = require('mongoose');
//鏈接數(shù)據(jù)庫(kù)
var db = mongoose.createConnection('mongodb://192.168.25.128:27017/fth');
//設(shè)置基礎(chǔ)的數(shù)據(jù)類型
var monSchema = new mongoose.Schema({
name:{type:String,default:'fengtianhe'},
age:{type:Number},
sex:{type:String}
});
//選擇數(shù)據(jù)庫(kù)的集合(mongodb默認(rèn)加個(gè)s)
var monModel = db.model('user',monSchema);
//設(shè)置條件
var tiaojian = {name:"fth"};
//設(shè)置要更新成的數(shù)據(jù)
var result = {$set:{name:'小強(qiáng)',age:'3'}};
monModel.update(tiaojian,result,function(err){
if(err){
console.log(err);
}else{
console.log('update is ok');
}
db.close();
});-
執(zhí)行并查看結(jié)果
-
編寫(xiě)刪除方法
//包含依賴庫(kù)
var mongoose = require('mongoose');
//鏈接數(shù)據(jù)庫(kù)
var db = mongoose.createConnection('mongodb://192.168.25.128:27017/fth');
//設(shè)置基礎(chǔ)的數(shù)據(jù)類型
var monSchema = new mongoose.Schema({
name:{type:String,default:'fengtianhe'},
age:{type:Number},
sex:{type:String}
});
//選擇數(shù)據(jù)庫(kù)的集合(mongodb默認(rèn)加個(gè)s)
var monModel = db.model('user',monSchema);
//設(shè)置刪除的條件
var tiaojian = {name:"fth"};monModel.remove(tiaojian,function(err){ if(err){ console.log(err); }else{ console.log('remove is ok'); } db.close(); });
執(zhí)行并查看結(jié)果