其實(shí)對(duì)于做一些常見(jiàn)的應(yīng)用拍鲤,增刪改查也就夠用了贴谎,數(shù)據(jù)庫(kù)的東西博大精深,不可一日耳語(yǔ)季稳,當(dāng)然擅这,我這是在寫(xiě)之前瞎掰了一下,不用在意景鼠。
1.Node.js連接mongodb數(shù)據(jù)庫(kù)并創(chuàng)建集合
const MongoClient = require('mongodb').MongoClient;
let url = "mongodb://localhost:27017/datas";
MongoClient.connect(url,(err,db)=>{
if(err){
throw(err);
}else{
console.log('數(shù)據(jù)庫(kù)已連接');
//db.close();
let dbBase = db.db("datas");
dbBase.createCollection("sec",(err,res)=>{
if(err){
throw(err);
}else{
console.log('創(chuàng)建集合');
}
});
}
})
2.插入數(shù)據(jù)insert
const MongoClient = require('mongodb').MongoClient;
let url = 'mongodb://localhost:27017/datas';
let insertData = function(db,callback){
let collection = db.db('datas').collection('sec'); //連接到集合sec
let data = [{title: 'mongodb',age: 15},{title: 'node.js',age: 18}];
collection.insert(data,(err,res)=>{
if(err){
console.log(err);
return;
}else{
callback(res);
}
});
}
MongoClient.connect(url,(err,db)=>{
if(err){
throw(err);
}else{
console.log('數(shù)據(jù)庫(kù)已連接');
insertData(db,(res)=>{
console.log(res);
});
}
})
3.查找數(shù)據(jù)find
const MongoClient = require('mongodb').MongoClient;
let url = 'mongodb://localhost:27017/datas';
let insertData = function(db,callback){
let collection = db.db('datas').collection('sec'); //連接到集合sec
let data = {title: 'mongodb'};
collection.find(data).toArray((err,res)=>{
if(err){
console.log(err);
return;
}else{
callback(res);
}
});
}
MongoClient.connect(url,(err,db)=>{
if(err){
throw(err);
}else{
console.log('數(shù)據(jù)庫(kù)已連接');
insertData(db,(res)=>{
console.log(res[0].title);
});
}
})
4.刪除數(shù)據(jù)deleteMany,當(dāng)然,還有deleteOne
const MongoClient = require('mongodb').MongoClient;
let url = 'mongodb://localhost:27017/datas';
let insertData = function(db,callback){
let collection = db.db('datas').collection('sec'); //連接到集合sec //這里菜鳥(niǎo)教程直接寫(xiě)的db.collection是錯(cuò)的
let data = {title: 'java教程'};
collection.deleteMany(data,(err,res)=>{
if(err){
console.log(err);
return;
}else{
callback(res);
}
});
}
MongoClient.connect(url,(err,db)=>{
if(err){
throw(err);
}else{
console.log('數(shù)據(jù)庫(kù)已連接');
insertData(db,(res)=>{
console.log(res);
});
}
})
5.更新數(shù)據(jù)update
const MongoClient = require('mongodb').MongoClient;
let url = 'mongodb://localhost:27017/datas';
let insertData = function(db,callback){
let collection = db.db('datas').collection('sec'); //連接到集合sec
let data = {title: 'mongodb'}; //舊數(shù)據(jù)
let updateData = {$set: {age: 20}}; //設(shè)置的新數(shù)據(jù)
collection.update(data,updateData,(err,res)=>{
if(err){
console.log(err);
return;
}else{
callback(res);
}
});
}
MongoClient.connect(url,(err,db)=>{
if(err){
throw(err);
}else{
console.log('數(shù)據(jù)庫(kù)已連接');
insertData(db,(res)=>{
console.log(res);
});
}
})