首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从Mongodb获取文档对象

如何从Mongodb获取文档对象
EN

Stack Overflow用户
提问于 2020-04-12 23:43:09
回答 1查看 417关注 0票数 0

我在MongoDB中记录了一些文档,我需要返回一个文档进行比较。

例如:

代码语言:javascript
运行
复制
{user_mail:'MAIL' , user_pass:'PASS'}

我知道如何找到它,但我如何访问它呢?我想要一个函数给我文件作为输出。

换言之:

代码语言:javascript
运行
复制
var A = function (*(data base name), (collection name), (condition to find document)*)

A应该是我的文档。

我对使用快递模块不感兴趣

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-13 03:19:28

试试这个:

文件 mongo-conn.js

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61179626

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档