javascript - 如何从 Mongodb 获取 Document 对象
问题描述
我在 MongoDB 中记录了一些文档,我需要返回一份文档进行比较。
例如:
{user_mail:'MAIL' , user_pass:'PASS'}
我知道如何找到它,但我怎样才能访问它?我想要一个可以将文档作为输出的函数。
换句话说:
var A = function (*(data base name), (collection name), (condition to find document)*)
A
我的文件应该在哪里。
PS 我对使用 Express 模块不感兴趣
解决方案
试试这个:
文件 mongo-conn.js
:
const mongo = require('mongodb');
const mongoClient = mongo.MongoClient;
const mongoConn = 'mongodb://localhost:27017/auth';
class MongoQuery {
async getCollections(dbName) {
try {
const client = this.db;
let list = await client.db(dbName).listCollections().toArray();
list = list.map(function (col) {
return col.name
})
await client.close();
return list;
}
catch (Ex) {
throw new Error(Ex);
}
}
async getResult(dbName, collectionName, condition = {}, limit = 0, skip = false, sort = { createdOn: -1 }, fields = { __v: 0 }) {
// console.log(`\ndbName ==> `, dbName, `,\ncollectionName ==> `, collectionName, `,\ncondition ==> `, condition, `,\nsort ==> `, sort, `,\nlimit ==> `, limit, `,\nskip ==> `, skip, `,\nfields ==> `, fields)
if (!this.db)
throw new Error('no connection established');
if (!dbName)
throw new Error('invalid dbName');
if (!collectionName)
throw new Error('invalid collectionName');
if (!sort || typeof sort != 'object')
throw new Error('invalid sort');
try {
let client = this.db, data = [];
if (limit && skip)
data = await client.db(dbName).collection(collectionName).find(condition, fields).sort(sort).skip(parseInt(skip)).limit(parseInt(limit)).toArray()
else if (limit)
data = await client.db(dbName).collection(collectionName).find(condition, fields).sort(sort).limit(parseInt(limit)).toArray()
else if (skip)
data = await client.db(dbName).collection(collectionName).find(condition, fields).sort(sort).skip(parseInt(skip)).toArray()
else {
data = await client.db(dbName).collection(collectionName).find(condition, fields).sort(sort).toArray()
}
await client.close();
return data;
}
catch (Ex) {
throw new Error(Ex);
}
}
async getAggregate(dbName, collectionName, aggregateArr) {
if (!this.db)
throw new Error('no connection established');
if (!dbName)
throw new Error('invalid dbName');
if (!collectionName)
throw new Error('invalid collectionName');
if (!Array.isArray(aggregateArr))
throw new Error('invalid aggregateArr');
console.log(dbName, collectionName, JSON.stringify(aggregateArr))
try {
let client = this.db, data = [];
data = await client.db(dbName).collection(collectionName).aggregate(aggregateArr).toArray()
await client.close();
return data;
}
catch (Ex) {
throw new Error(Ex);
}
}
async getResultCount(dbName, collectionName, condition = {}) {
if (!this.db)
throw new Error('no connection established');
if (!dbName)
throw new Error('invalid dbName');
if (!collectionName)
throw new Error('invalid collectionName');
console.log(`\ndbName ==> `, dbName, `,\ncollectionName ==> `, collectionName, `,\ncondition ==> `, condition)
try {
let client = this.db, count = 0;
count = await client.db(dbName).collection(collectionName).count(condition)
await client.close();
return count;
}
catch (Ex) {
throw new Error(Ex);
}
}
async getDistinctResult(dbName, collectionName, distinctKey, condition = {}) {
if (!this.db)
throw new Error('no connection established');
if (!dbName)
throw new Error('invalid dbName');
if (!collectionName)
throw new Error('invalid collectionName');
if (!distinctKey)
throw new Error('invalid distinctKey');
console.log(`\ndbName ==> `, dbName, `,\ncollectionName ==> `, collectionName, `,\distinctKey ==> `, distinctKey, `,\ncondition ==> `, condition)
try {
let client = this.db, data = [];
data = await client.db(dbName).collection(collectionName).distinct(distinctKey.toString(), condition)
await client.close();
return data;
}
catch (Ex) {
throw new Error(Ex);
}
}
async getDistinctResultCount(dbName, collectionName, distinctKey, condition = {}) {
if (!this.db)
throw new Error('no connection established');
if (!dbName)
throw new Error('invalid dbName');
if (!collectionName)
throw new Error('invalid collectionName');
if (!distinctKey)
throw new Error('invalid distinctKey');
console.log(`\ndbName ==> `, dbName, `,\ncollectionName ==> `, collectionName, `,\distinctKey ==> `, distinctKey, `,\ncondition ==> `, condition)
try {
let client = this.db, count = 0;
count = await client.db(dbName).collection(collectionName).distinct(distinctKey.toString(), condition).length
await client.close();
return count;
}
catch (Ex) {
throw new Error(Ex);
}
}
async saveResult(dbName, collectionName, result) {
if (!this.db)
throw new Error('no connection established');
if (!dbName)
throw new Error('invalid dbName');
if (!collectionName)
throw new Error('invalid collectionName');
console.log(`\ndbName ==> save `, dbName, `,\ncollectionName ==> `, collectionName)
try {
let db = this.db, savedResult = {};
savedResult = await db.collection(collectionName).insert(result);
await db.close();
return savedResult;
}
catch (Ex) {
throw new Error(Ex);
}
}
async saveResultMultiple(dbName, collectionName, result) {
if (!this.db)
throw new Error('no connection established');
if (!dbName)
throw new Error('invalid dbName');
if (!collectionName)
throw new Error('invalid collectionName');
console.log(`\ndbName ==> save `, dbName, `,\ncollectionName ==> `, collectionName)
try {
let db = this.db, savedResult = {};
savedResult = await db.collection(collectionName).insertMany(result);
await db.close();
return savedResult;
}
catch (Ex) {
throw new Error(Ex);
}
}
makeMongoId(id) {
// console.log('makeMongoId ==>', id)
const mongoose = require('mongoose');
try {
return mongoose.Types.ObjectId(id)
}
catch (Ex) {
console.log('makeMongoId Ex ==> ', Ex)
return Ex
}
}
validateMongoId(id) {
console.log('validateMongoId ==>', id)
const mongoose = require('mongoose');
try {
return mongoose.Types.ObjectId.isValid(id)
}
catch (Ex) {
console.log('validateMongoId Ex ==> ', Ex)
return false
}
}
}
class MongoConnections extends MongoQuery {
constructor() {
super()
this.db = null
}
async connectDb(uri) {
if (uri) {
mongoConn = uri
}
try {
const options = {
// autoReconnect: true,
poolSize: 10,
socketTimeoutMS: 90000,
connectTimeoutMS: 90000,
reconnectTries: 30,
reconnectInterval: 1000,
useUnifiedTopology: true
};
this.db = await mongoClient.connect(mongoConn, options);
return
} catch (dbError) {
console.log(`MongoDb connection error. ${dbError}`);
throw new Error(dbError);
}
}
}
module.exports = new MongoConnections
文件 test.js
const mongo = require('./mongo-conn')
async function showData() {
await mongo.connectDb()
let condition = {}
let data = await mongo.getResult('dbName', 'collectionName', condition)
console.log(data)
}
showData()
推荐阅读
- swift - 在 Swift 中查找父调用者文件、行号和函数
- python - 我需要帮助从类函数的列表中删除条目
- ios - 您好,我正在使用 swift,我正在尝试在选择集合视图单元格时更改集合视图单元格的标签
- javascript - 如果我从 .json 中提取具有自动重定向的 url,如何使输出成为我将被重定向到的页面?- Javascript
- python - 如何使用 cv2 创建一个判断图像是否在另一个图像中的 True 或 False 函数
- azure-devops - 在 Azure YAML 管道的脚本阶段下添加多个命令
- django - 如何使用 django 从我选择的特定数据库表中登录用户
- python - 二维数组的水平和垂直邻居
- java - 如何处理maven内部依赖?
- java - 在每个事务结束时解除对环境的锁定