简体   繁体   English

如何从 Mongodb 获取文档 object

[英]How to get Document object from Mongodb

I have recorded some documents in MongoDB and I need to return one of my documents to compare.我在 MongoDB 中记录了一些文件,我需要返回一份文件进行比较。

For example:例如:

{user_mail:'MAIL' , user_pass:'PASS'}

I know how to find it but how can I access it?我知道如何找到它,但我怎样才能访问它? I want a function which would give me the document as output.我想要一个 function,它会给我文件 output。

In other words:换句话说:

var A = function (*(data base name), (collection name), (condition to find document)*)

Where A should be my document. A应该是我的文件。

PS I am not interested in using Express module PS 我对使用 Express 模块不感兴趣

Try this:尝试这个:
File mongo-conn.js :文件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

File test.js文件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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM