1.創(chuàng)建一個MongoDB模塊
var mongodb = require('mongodb');
var server = mongodb.Server('192.168.1.114',27017,{});
var client = new mongodb.Db('education',server,{w:true});
openclient();
function openclient(){
client.open(function(error,client){
if(error){
console.error(error);
}else{
console.log('(1).openclient successful');
openCollection();
}
});
}
創(chuàng)建一個MongoDB的模塊,并創(chuàng)建一個名為“education”的系統(tǒng),將其打開刷钢。
2. 打開所創(chuàng)建的系統(tǒng)模塊中的某個文檔
function openCollection(){
client.collection('student',function(error,collection){
if(error){
console.error(error);
}else{
console.log("(2).openCollection successful");
// insertMsg(collection);
inquireAboutMsg(collection);
// updateMsg(collection);
// deleteMsg(collection);
}
});
}
打開所屬于client下面的collection文檔,并且查詢信息inquireAboutMsg(collection);
3.在collection文檔中插入信息
function insertMsg(collection){
var studentX = {studentId:14404233,studentName:'xuan',studentScore:100};
var studentH = {studentId:14404239,studentName:'HJ',studentScore:99};
var studentF = {studentId:14404235,studentName:'huanhuan',studentScore:88};
var student = [studentX,studentH,studentF];//插入多個對象到collection里面
collection.insert(student,{safe:true},function(error,student){
if(error){
console.error(error);
}else{
console.log('(3).insertMsg successful');
console.log(student);
}
});
}
collection.insert(student,{safe:true},function(error,student)
這里的的student是插入collection中的信息。
4.查詢collection中的所有信息
function inquireAboutMsg(collection){
collection.find({}).toArray(function(error,student){
if(error){
console.error(error);
}else{
console.log('(4). inquireAboutMsg successful');
console.log(student);//這里的student參數(shù)是查看當前collection里面的所有信息
}
});
}
find里面寫空則是查詢collection中的所有信息警医。
5 .更新collection中的信息
function updateMsg(collection){
var callback = function(error,student){
if(error){
console.error(error);
}else{
console.log('(5).update successful');
console.log(student);//這里的student參數(shù)是更新的個數(shù)
}
}
collection.update({},{$set:{studentSex:'female'}},{multi:true},callback);//multi為true的時候更新collection里面的所有信息
}
6.刪除collection中的信息
function deleteMsg(collection){
collection.remove({studentId:14404233},null,function(error,student){
if(error){
console.error(error);
}else{
console.log('(6).remove successful');
console.log(student);//這里的student參數(shù)是刪除的個數(shù)
}
});
}
romove 中的參數(shù)限定了刪除哪些信息.