首页 > 解决方案 > 我需要一遍又一遍地连接到 Mongo 吗?

问题描述

我正在制作一个不和谐的机器人。当我使用java时,我通过为我的机器人所在的每台服务器创建不同的数据库将数据保存到mongo,但是在javascript上我只能使用一个数据库。它让我连接/查看的唯一数据库是测试数据库,除了它将所有内容显示为未定义。Mongo js 文档告诉我一遍又一遍地连接到数据库,但是当使用 java 时,我只是在 bot 启动时连接,并且可以随时使用它。我尝试了在 stackoverflow 上可以找到的所有示例,但没有一个对我有帮助。

应用程序.js:

require("./handler/mongo")();
client.on("ready", () => {
        console.log(global.mongoclient.db("574612262275252231").collection("settings").find({})); 
}

mongo.js:

const mongo = require('mongodb').MongoClient;
module.exports = function(){
    mongo.connect(uri, (err, client) => {
        if(err) throw err;
        global.mongoclient = client;
        console.log("a");
    });
}

控制台输出:

a
Cursor {
  _readableState: ReadableState {
    objectMode: true,
    highWaterMark: 16,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: [],
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    sync: true,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: false,
    destroyed: false,
    defaultEncoding: 'utf8',
    awaitDrainWriters: null,
    multiAwaitDrain: false,
    readingMore: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  readable: true,
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  operation: FindOperation {
    options: {
      skip: 0,
      limit: 0,
      raw: undefined,
      hint: null,
      timeout: undefined,
      slaveOk: true,
      readPreference: [ReadPreference],
      db: [Db],
      promiseLibrary: [Function: Promise]
    },
    ns: MongoDBNamespace {
      db: '574612262275252231',
      collection: 'settings'
    },
    cmd: {
      find: '574612262275252231.settings',
      limit: 0,
      skip: 0,
      query: {},
      raw: undefined,
      hint: null,
      timeout: undefined,
      slaveOk: true,
      readPreference: [ReadPreference]
    },
    readPreference: ReadPreference { mode: 'primary', tags: undefined },
    cursorState: {
      cursorId: null,
      cmd: [Object],
      documents: [],
      cursorIndex: 0,
      dead: false,
      killed: false,
      init: false,
      notified: false,
      limit: 0,
      skip: 0,
      batchSize: 1000,
      currentLimit: 0,
      transforms: undefined,
      raw: undefined
    }
  },
  pool: null,
  server: null,
  disconnectHandler: undefined,
  bson: undefined,
  ns: '574612262275252231.settings',
  namespace: MongoDBNamespace { db: '574612262275252231', collection: 'settings' },
  cmd: {
    find: '574612262275252231.settings',
    limit: 0,
    skip: 0,
    query: {},
    raw: undefined,
    hint: null,
    timeout: undefined,
    slaveOk: true,
    readPreference: ReadPreference { mode: 'primary', tags: undefined }
  },
  options: {
    skip: 0,
    limit: 0,
    raw: undefined,
    hint: null,
    timeout: undefined,
    slaveOk: true,
    readPreference: ReadPreference { mode: 'primary', tags: undefined },
    db: Db {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      s: [Object],
      serverConfig: [Getter],
      bufferMaxEntries: [Getter],
      databaseName: [Getter],
      [Symbol(kCapture)]: false
    },
    promiseLibrary: [Function: Promise]
  },
  topology: ReplSet {
    _events: [Object: null prototype] {
      authenticated: [Function (anonymous)],
      error: [Array],
      timeout: [Array],
      close: [Array],
      parseError: [Array],
      reconnect: [Array],
      commandStarted: [Function (anonymous)],
      commandSucceeded: [Function (anonymous)],
      commandFailed: [Function (anonymous)],
      serverOpening: [Function (anonymous)],
      serverClosed: [Function (anonymous)],
      serverDescriptionChanged: [Function (anonymous)],
      serverHeartbeatStarted: [Function (anonymous)],
      serverHeartbeatSucceeded: [Function (anonymous)],
      serverHeartbeatFailed: [Function (anonymous)],
      topologyOpening: [Function (anonymous)],
      topologyClosed: [Function (anonymous)],
      topologyDescriptionChanged: [Function (anonymous)],
      joined: [Function (anonymous)],
      left: [Function (anonymous)],
      ping: [Function (anonymous)],
      ha: [Function (anonymous)],
      connectionPoolCreated: [Function (anonymous)],
      connectionPoolClosed: [Function (anonymous)],
      connectionCreated: [Function (anonymous)],
      connectionReady: [Function (anonymous)],
      connectionClosed: [Function (anonymous)],
      connectionCheckOutStarted: [Function (anonymous)],
      connectionCheckOutFailed: [Function (anonymous)],
      connectionCheckedOut: [Function (anonymous)],
      connectionCheckedIn: [Function (anonymous)],
      connectionPoolCleared: [Function (anonymous)],
      open: [Function],
      fullsetup: [Function],
      all: [Function]
    },
    _eventsCount: 35,
    _maxListeners: Infinity,
    s: {
      coreTopology: [ReplSet],
      sCapabilities: [ServerCapabilities],
      tag: undefined,
      storeOptions: [Object],
      clonedOptions: [Object],
      store: [Store],
      options: [Object],
      sessionPool: [ServerSessionPool],
      sessions: Set(0) {},
      promiseLibrary: [Function: Promise]
    },
    [Symbol(kCapture)]: false
  },
  cursorState: {
    cursorId: null,
    cmd: {
      find: '574612262275252231.settings',
      limit: 0,
      skip: 0,
      query: {},
      raw: undefined,
      hint: null,
      timeout: undefined,
      slaveOk: true,
      readPreference: [ReadPreference]
    },
    documents: [],
    cursorIndex: 0,
    dead: false,
    killed: false,
    init: false,
    notified: false,
    limit: 0,
    skip: 0,
    batchSize: 1000,
    currentLimit: 0,
    transforms: undefined,
    raw: undefined
  },
  logger: Logger { className: 'Cursor' },
  s: {
    numberOfRetries: 5,
    tailableRetryInterval: 500,
    currentNumberOfRetries: 5,
    state: 0,
    promiseLibrary: [Function: Promise],
    explicitlyIgnoreSession: false
  },
  [Symbol(kCapture)]: false
}

标签: mongodb

解决方案


Mongo js 文档告诉我一遍又一遍地连接到数据库

这些只是例子。如果您愿意,您可以拥有一个全球客户(这对实际应用程序很有意义)。


推荐阅读