Node封装mongodb的增删改查

  1. 安装第三方插件: cnpm i mongodb ,这里的版本是最新"mongodb": "^5.0.0",

  1. 参考官网:https://www.npmjs.com/package/mongodb

代码:

const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'

// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'shallowDB';
 /**
    * 查询表格数据
    * @param {String} table 表格名称 
    * @param {any} data 查询条件是一个对象
    */
const findMemo = async function findMemo(table,data={}) {
    // Use connect method to connect to the server
    await client.connect();
    console.log('Connected successfully to server');
    const db = client.db(dbName);
    const collection = db.collection(table);

    // the following code examples can be pasted here...
    const findResult = await collection.find(data).toArray();
    // console.log('Found documents =>', findResult);
    return findResult;
}
/**
 * 添加表格数据
 * @param {*} table 表格名称
 * @param {*} data 添加的数组 []
 * @returns 
 */
const addMemo = async function addMemo(table,data=[]) {
    await client.connect();
    console.log('Connected successfully to server');
    const db = client.db(dbName);
    const collection = db.collection(table);

    const insertResult = await collection.insertMany(data);
    return insertResult;
}
/**
 * 更新文档
 * @param {*} table 表格名称
 * @param {*} data 是一个对象,查询条件
 * @param {*} content 更新的内容,是一个对象 eg:{$set:{b:9}}
 * @returns 
 */
const updateMemo = async function updateMemo(table,data={},content) {
    await client.connect();
    console.log('Connected successfully to server');
    const db = client.db(dbName);
    const collection = db.collection(table);

    const updateResult = await collection.updateOne(data,content);
    return updateResult;
}
/**
 * 删除文档
 * @param {*} table 表格名字
 * @param {*} data 删除的条件,是一个对象
 * @returns 
 */
const delMemo = async function findMemo(table,data={}) {
    await client.connect();
    console.log('Connected successfully to server');
    const db = client.db(dbName);
    const collection = db.collection(table);

    const deleteResult = await collection.deleteMany(data);
    return deleteResult;
}

module.exports = {
    findMemo, addMemo, updateMemo, delMemo
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值