当前位置: 首页 > 后端技术 > Node.js

MongoDB操作

时间:2023-04-03 17:23:09 Node.js

MongoDB加载mongodbconstMongoClient=require('mongodb').MongoClient;constresuleSet=require('./resultSet');//数据库地址consturl='mongodb://localhost:27017';//数据库名称constdbName='user';让db={};连接到数据库MongoClient.connect(url,function(err,client){db=client.db(dbName);});数据库操作module.exports={//collection是集合,filter是过滤,data是数据//获取数据asyncselect(collection,filter={}){//db.collection.find()这个方法获取多块数据constresult=awaitdb.collection(collection).find(filter).toArray();returnresuleSet(result.length>0,result);},//添加数据asyncinsert(collection,data){//db.collection.insert()该方法插入一个或多个Dataconstresult=awaitdb.collection(collection).insert(data);returnresuleSet(result.length>0,result);},//更新数据asyncupdate(collection,filter,data){//db.collection.update()该方法更新多条数据constresult=awaitdb.collection(collection).update(filter,data);返回结果eSet(result.length>0,result);},//删除数据asyncdelete(collection,filter){//db.collection.deleteOne()此方法从集合中删除单个文档constresult=awaitdb.collection(collection)。删除一个(过滤器);returnresuleSet(result.length>0,result);},};