安装第三方插件: cnpm i mongodb ,这里的版本是最新"mongodb": "^5.0.0",
代码:
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
};