本課重點(diǎn):學(xué)習(xí)Node.js連接MongoDB數(shù)據(jù)庫操作,并實(shí)現(xiàn)基本的數(shù)據(jù)庫增、刪、改、查操作。
1.安裝Mongodb組件及Mongoose組件來對(duì)MongoDB數(shù)據(jù)庫進(jìn)行操作。
首先在自己的項(xiàng)目目錄中執(zhí)行 npm init安裝mongodb命令。
npm install mongodb --save
然后緊接著執(zhí)行Mongoose安裝命令。
npm install mongoose
2.連接MongoDB
首先,我們需要定義一個(gè)連接。如果您的應(yīng)用程序只使用一個(gè)數(shù)據(jù)庫,您應(yīng)該使用 mongoose.connect。如果您需要?jiǎng)?chuàng)建額外的連接,使用 mongoose.createConnection.
這兩個(gè) connect和 createConnection取一個(gè) mongodb://URI或參數(shù) host, database, port, options.
//加載組件
var mongoose =require('mongoose');
//創(chuàng)建數(shù)據(jù)庫連接
mongoose.createConnection('mongodb://localhost/my_database');
3.定義要?jiǎng)?chuàng)建的集合模型
定義數(shù)據(jù)類型:
var monSchema = new mongoose.Schema({
name:{ type:String,default:'zhangsan'},
age:{ type:Number},
sex:{ type:String}
});
創(chuàng)建模型:
var monModel = db.model('user',monSchema);
設(shè)定數(shù)據(jù)內(nèi)容:
var content = {name:'張三',age:18,性別:'男'};
創(chuàng)建實(shí)例并執(zhí)行操作:
var monInsert = new monModel(content);
monInsert.save(function(err){
if(err){
console.log(err);
}else{
console.log('數(shù)據(jù)寫入成功!');
}
db.close();
});
查詢操作
先定義好要查詢的字段:
var field = {name:1,age:1,sex:1};//其中1為占位符
定義查詢條件:
var content = {name:'張三'};
執(zhí)行查詢操作:
monModel.find(content,field,function(err,result){
if(err){
console.log(err);
}else{
console.log(result);
}
db.close();
});
修改操作
定義要修改數(shù)據(jù)的條件:
var tiaojian = {name:'張三'};
設(shè)置修改的數(shù)據(jù):
var updateData = {$set:{name:'李四',age:3}};
執(zhí)行修改操作:
monModel.update(tiaojian,updateData,function(err){
if(err){
console.log(err);
}else{
console.log('update is OK!');
}
db.close();
});
刪除操作
定義要?jiǎng)h除的條件:
var tiaojian = {name:'李四'};
執(zhí)行刪除操作:
monModel.remove(tiaojian,function(err){
if(err){
console.log(err);
}else{
console.log('刪除成功!');
}
db.close();
});