MongoDB操做

MongoDB

  1. 加載 mongodbmongodb

    const MongoClient = require('mongodb').MongoClient;
     const resuleSet = require('./resultSet');
     
     //數據庫地址
     const url = 'mongodb://localhost:27017';
     //數據庫名稱
     const dbName = 'user';
     
     let db = {};
  2. 鏈接數據庫數據庫

    MongoClient.connect(url, function(err, client) {
       db = client.db(dbName);
     });
  3. 數據庫操做async

    module.exports = {
       //collection爲集合,filter爲過濾,data爲數據
       //獲取數據
       async select(collection, filter = {}) {
         //db.collection.find()該方法獲取多條數據
         const result = await db.collection(collection).find(filter).toArray();
         return resuleSet(result.length > 0, result);
       },
     
       //添加數據
       async insert(collection, data) {
         //db.collection.insert()該方法插入一條或多條數據
         const result = await db.collection(collection).insert(data);
         return resuleSet(result.length > 0, result);
       },
     
       //更新數據
       async update(collection, filter, data) {
         //db.collection.update()該方法更新多條數據
         const result = await db.collection(collection).update(filter, data);
         return resuleSet(result.length > 0, result);
       },
     
       //刪除數據
       async delete(collection, filter) {
         //db.collection.deleteOne() 該方法從集合中刪除單個文檔
         const result = await db.collection(collection).deleteOne(filter);
         return resuleSet(result.length > 0, result);
       },
     };
相關文章
相關標籤/搜索