mongoose 错误:当我创建Grid(db,mongo)时缺少db参数

vx6bjr1n  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(85)

我使用gridfs来存储monogodb中的文件,当我检索文件到数据库时,我使Grid类型对象,但这里的错误是缺少db参数如何解决这个问题

import mongoose from "mongoose";
import Folders from "../models/Folder.js";
import path from "path";
import Grid from "gridfs-stream";
import fs from "fs";

const connection = mongoose.connection;
// Grid.mongo = mongoose.mongo;
// const gfs = Grid(mongoose.connection.db, mongoose.mongo);
// Grid.mongo = mongoose.mongo;
const db = mongoose.connection.db;
const mongo = mongoose.mongo;
var gfs = Grid(db,mongo);

字符串
这里输出:


的数据

bvn4nwqk

bvn4nwqk1#

Connection.prototype.db文档:
mongodb.Db示例,打开连接时设置
这意味着mongoose.connection.db将在连接打开时设置。在连接打开之前,值为undefined。这就是为什么你会得到错误,gridfs-stream库将验证这里的参数1.1.1/lib/index.js#L25
首先使用mongoose.connect()方法连接数据库服务器。

import Grid from 'gridfs-stream';
import mongoose from 'mongoose';
import { config } from '../../config';

(async function main() {
    try {
        console.log('Before DB connected: ', mongoose.connection.db);
        await mongoose.connect(config.MONGODB_URI);
        const { db } = mongoose.connection;
        console.log('DB connected: ', db);
        const mongo = mongoose.mongo;

        const gfs = Grid(db, mongo);
        console.log(gfs);
    } catch (error) {
        console.error(error);
    } finally {
        await mongoose.connection.close();
    }
})();

字符串
日志:

Before DB connected:  undefined
DB connected:  Db {
  s: {
    options: {
      enableUtf8Validation: true,
      forceServerObjectId: false,
      pkFactory: [Object],
      raw: false,
      readPreference: [ReadPreference],
      retryWrites: true
    },
    readPreference: ReadPreference {
      mode: 'primary',
      tags: undefined,
      hedge: undefined,
      maxStalenessSeconds: undefined,
      minWireVersion: undefined
    },
    bsonOptions: {
      raw: false,
      useBigInt64: false,
      promoteLongs: true,
      promoteValues: true,
      promoteBuffers: false,
      ignoreUndefined: false,
      bsonRegExp: false,
      serializeFunctions: false,
      fieldsAsRaw: {},
      enableUtf8Validation: true
    },
    pkFactory: { createPk: [Function: createPk] },
    readConcern: undefined,
    writeConcern: undefined,
    namespace: MongoDBNamespace { db: 'test', collection: undefined }
  },
  client: <ref *1> MongoClient {
    _events: [Object: null prototype] {
      topologyDescriptionChanged: [Function (anonymous)]
    },
    _eventsCount: 1,
    _maxListeners: 0,
    mongoLogger: MongoLogger {
      error: [Function: bound log],
      warn: [Function: bound log],
      info: [Function: bound log],
      debug: [Function: bound log],
      trace: [Function: bound log],
      componentSeverities: [Object],
      maxDocumentLength: 1000,
      logDestination: [Object]
    },
    s: {
      url: 'mongodb+srv://slideshowp2:xtEBJWGgFXSNbv6t@cluster0.d1avjia.mongodb.net',
      bsonOptions: [Object],
      namespace: [MongoDBNamespace],
      hasBeenClosed: false,
      sessionPool: [ServerSessionPool],
      activeSessions: Set(0) {},
      options: [Getter],
      readConcern: [Getter],
      writeConcern: [Getter],
      readPreference: [Getter],
      isMongoClient: [Getter]
    },
    connectionLock: undefined,
    topology: Topology {
      _events: [Object: null prototype],
      _eventsCount: 26,
      _maxListeners: undefined,
      client: [Circular *1],
      selectServerAsync: [Function (anonymous)],
      s: [Object],
      [Symbol(kCapture)]: false,
      [Symbol(waitQueue)]: [List]
    },
    [Symbol(kCapture)]: false,
    [Symbol(options)]: [Object: null prototype] {
      hosts: [Array],
      credentials: [MongoCredentials],
      compressors: [Array],
      connectTimeoutMS: 30000,
      directConnection: false,
      driverInfo: [Object],
      enableUtf8Validation: true,
      forceServerObjectId: false,
      heartbeatFrequencyMS: 10000,
      keepAlive: true,
      keepAliveInitialDelay: 120000,
      loadBalanced: false,
      localThresholdMS: 15,
      maxConnecting: 2,
      maxIdleTimeMS: 0,
      maxPoolSize: 100,
      minPoolSize: 0,
      minHeartbeatFrequencyMS: 500,
      monitorCommands: false,
      noDelay: true,
      pkFactory: [Object],
      raw: false,
      readPreference: [ReadPreference],
      retryReads: true,
      retryWrites: true,
      serverSelectionTimeoutMS: 30000,
      socketTimeoutMS: 0,
      srvMaxHosts: 0,
      srvServiceName: 'mongodb',
      waitQueueTimeoutMS: 0,
      zlibCompressionLevel: 0,
      dbName: 'test',
      userSpecifiedAuthSource: false,
      userSpecifiedReplicaSet: false,
      srvHost: 'cluster0.d1avjia.mongodb.net',
      tls: true,
      mongoLoggerOptions: [Object],
      metadata: [Object],
      replicaSet: 'atlas-zy5qpa-shard-0',
      [Symbol(@@mdb.enableMongoLogger)]: false
    }
  }
}
Grid {
  db: Db {
    s: {
      options: [Object],
      readPreference: [ReadPreference],
      bsonOptions: [Object],
      pkFactory: [Object],
      readConcern: undefined,
      writeConcern: undefined,
      namespace: [MongoDBNamespace]
    },
    client: MongoClient {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: 0,
      mongoLogger: [MongoLogger],
      s: [Object],
      connectionLock: undefined,
      topology: [Topology],
      [Symbol(kCapture)]: false,
      [Symbol(options)]: [Object: null prototype]
    }
  },
  mongo: {
    BSON: [Getter],
    Binary: [Getter],
    BSONRegExp: [Getter],
    BSONSymbol: [Getter],
    BSONType: [Getter],
    Code: [Getter],
    DBRef: [Getter],
    Decimal128: [Getter],
    Double: [Getter],
    Int32: [Getter],
    Long: [Getter],
    MaxKey: [Getter],
    MinKey: [Getter],
    ObjectId: [Getter],
    Timestamp: [Getter],
    MongoBulkWriteError: [Getter],
    ChangeStreamCursor: [Getter],
    MongoAPIError: [Getter],
    MongoAWSError: [Getter],
    MongoBatchReExecutionError: [Getter],
    MongoChangeStreamError: [Getter],
    MongoCompatibilityError: [Getter],
    MongoCursorExhaustedError: [Getter],
    MongoCursorInUseError: [Getter],
    MongoDecompressionError: [Getter],
    MongoDriverError: [Getter],
    MongoError: [Getter],
    MongoExpiredSessionError: [Getter],
    MongoGridFSChunkError: [Getter],
    MongoGridFSStreamError: [Getter],
    MongoInvalidArgumentError: [Getter],
    MongoKerberosError: [Getter],
    MongoMissingCredentialsError: [Getter],
    MongoMissingDependencyError: [Getter],
    MongoNetworkError: [Getter],
    MongoNetworkTimeoutError: [Getter],
    MongoNotConnectedError: [Getter],
    MongoParseError: [Getter],
    MongoRuntimeError: [Getter],
    MongoServerClosedError: [Getter],
    MongoServerError: [Getter],
    MongoServerSelectionError: [Getter],
    MongoSystemError: [Getter],
    MongoTailableCursorError: [Getter],
    MongoTopologyClosedError: [Getter],
    MongoTransactionError: [Getter],
    MongoUnexpectedServerResponseError: [Getter],
    MongoWriteConcernError: [Getter],
    AbstractCursor: [Getter],
    Admin: [Getter],
    AggregationCursor: [Getter],
    CancellationToken: [Getter],
    ChangeStream: [Getter],
    ClientSession: [Getter],
    Collection: [Getter],
    Db: [Getter],
    FindCursor: [Getter],
    GridFSBucket: [Getter],
    GridFSBucketReadStream: [Getter],
    GridFSBucketWriteStream: [Getter],
    ListCollectionsCursor: [Getter],
    ListIndexesCursor: [Getter],
    MongoClient: [Getter],
    OrderedBulkOperation: [Getter],
    UnorderedBulkOperation: [Getter],
    BatchType: [Getter],
    GSSAPICanonicalizationValue: [Getter],
    AuthMechanism: [Getter],
    Compressor: [Getter],
    CURSOR_FLAGS: [Getter],
    AutoEncryptionLoggerLevel: [Getter],
    MongoErrorLabel: [Getter],
    ExplainVerbosity: [Getter],
    ServerApiVersion: [Getter],
    ReturnDocument: [Getter],
    ProfilingLevel: [Getter],
    ReadConcernLevel: [Getter],
    ReadPreferenceMode: [Getter],
    ServerType: [Getter],
    TopologyType: [Getter],
    ReadConcern: [Getter],
    ReadPreference: [Getter],
    WriteConcern: [Getter],
    CommandFailedEvent: [Getter],
    CommandStartedEvent: [Getter],
    CommandSucceededEvent: [Getter],
    ConnectionCheckedInEvent: [Getter],
    ConnectionCheckedOutEvent: [Getter],
    ConnectionCheckOutFailedEvent: [Getter],
    ConnectionCheckOutStartedEvent: [Getter],
    ConnectionClosedEvent: [Getter],
    ConnectionCreatedEvent: [Getter],
    ConnectionPoolClearedEvent: [Getter],
    ConnectionPoolClosedEvent: [Getter],
    ConnectionPoolCreatedEvent: [Getter],
    ConnectionPoolMonitoringEvent: [Getter],
    ConnectionPoolReadyEvent: [Getter],
    ConnectionReadyEvent: [Getter],
    ServerClosedEvent: [Getter],
    ServerDescriptionChangedEvent: [Getter],
    ServerHeartbeatFailedEvent: [Getter],
    ServerHeartbeatStartedEvent: [Getter],
    ServerHeartbeatSucceededEvent: [Getter],
    ServerOpeningEvent: [Getter],
    TopologyClosedEvent: [Getter],
    TopologyDescriptionChangedEvent: [Getter],
    TopologyOpeningEvent: [Getter],
    SrvPollingEvent: [Getter]
  },
  curCol: 'fs'
}


软件包版本:

"gridfs-stream": "^1.1.1",
"mongoose": "^7.3.1",

相关问题