1----Node.js封装mongodb增删改查
2----调用封装好的增删改查
const MongoClient = require("mongodb"). MongoClient; const url="mongodb://localhost:27017"; //增 删 改 查 function connect(callback){ MongoClient.connect(url,(err,db)=>{ if(err) throw err; callback(db) }) } //增 module.exports.insert=(dbname,colname,obj,callback)=>{ connect((db)=>{ if(!(obj instanceof Array)){ obj=[obj] } db.db(dbname).collection(colname).insertMany(obj,(err,result)=>{ if(err) throw err; console.log("插入数据成功"); db.close(); callback(result); }) }) } //删 module.exports.del=(dbname,colname,obj,callback)=>{ connect((db)=>{ db.db(dbname).collection(colname).deleteMany(obj,(err,result)=>{ if(err) throw err; console.log("删除"); db.close(); callback(result) }) }) } //改 module.exports.update=(dbname,colname,obj,ob,callback)=>{ connect((db)=>{ db.db(dbname).collection(colname).updateMany(obj,{$set:ob},(err,result)=>{ if(err) throw err; console.log("改"); db.close(); callback(result); }) }) } //查 module.exports.find=(dbname,colname,obj,callback)=>{ connect((db)=>{ db.db(dbname).collection(colname).find(obj).toArray((err,result)=>{ if(err) throw err; console.log("查询成功"); callback(result); }) }) }
2----调用封装好的增删改查
const express=require('express'); const app=express(); const dao=require("./feng.js"); //增 app.use('/insert',(req,res)=>{ dao.insert("teacher","class",[{age:"123",address:"北京"}],(a)=>{ if(a) res.send("插入成功") }) }) //查 app.use("/find",(req,res)=>{ dao.find("teacher",'class',{age:"123"},(a)=>{ if(a) res.send(a) }) }) //改 app.use("/update",(req,res)=>{ dao.update("teacher",'class',{age:"123"},{age:"11111"},(a)=>{ if(a) res.send("修改成功") }) }) //删 app.use('/del',(req,res)=>{ dao.del("teacher","class",{address:"北京"},(a)=>{ if(a) res.send("删除成功") }) }) app.listen('8989')