Node.js操作MongoDB数据库的基本操作(增删改查)

其实对于做一些常见的应用,增删改查也就够用了,数据库的东西博大精深,不可一日耳语,当然,我这是在写之前瞎掰了一下,不用在意。

1.Node.js连接mongodb数据库并创建集合

const MongoClient = require('mongodb').MongoClient;
let url = "mongodb://localhost:27017/datas";
MongoClient.connect(url,(err,db)=>{
  if(err){
    throw(err);
  }else{
    console.log('数据库已连接');
    //db.close();
    let dbBase = db.db("datas");
    dbBase.createCollection("sec",(err,res)=>{
      if(err){
        throw(err);
      }else{
        console.log('创建集合');
      }
    });
  }
})

2.插入数据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('数据库已连接');
    insertData(db,(res)=>{
      console.log(res);
    });
  }
})

3.查找数据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('数据库已连接');
    insertData(db,(res)=>{
      console.log(res[0].title);
    });
  }
})

4.删除数据deleteMany,当然,还有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 //这里菜鸟教程直接写的db.collection是错的
  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('数据库已连接');
    insertData(db,(res)=>{
      console.log(res);
    });
  }
})

5.更新数据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'}; //旧数据
  let updateData = {$set: {age: 20}}; //设置的新数据
  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('数据库已连接');
    insertData(db,(res)=>{
      console.log(res);
    });
  }
})

你可能感兴趣的:(Node.js操作MongoDB数据库的基本操作(增删改查))