"Cannot read property 'once' of undefined" 尝试将 gridfs 用于 mongodb

"Cannot read property 'once' of undefined" when using trying to use gridfs for mongodb

我正在尝试使用 gridfs 将文件上传到我的系统。 我在尝试将 mongodb 连接到 gridfs 时遇到问题 我只使用其文档中的 gridfs 连接。 应用程序文件:

// DB Config

const db = require("./mongoos1.js");

// Connect to MongoDB
const conn = db.connect((err) => {
    if (err) {
        console.log('unable to connect to database');
        process.exit(1);
    }

    else {
        app.listen(5000, () => {
            console.log('connected to database, app listening on port 5000');
        });
    }
});
// Init gfs
let gfs;

conn.once('open', () => {
  // Init stream
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection('uploads');
});

猫鼬文件:

const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
const dbname = "FYP";
const url = "mongodb://localhost:27017/FYP";
const mongoOptions = { useNewUrlParser: true };

const state = {

    db: null
};


const connect = (cb) => { // connect method
    if (state.db) //if there is connection
        cb();
    else { // if there isn't
        MongoClient.connect(url, mongoOptions, (err, client) => { // we use mongoclient to connect
            if (err)
                cb(err);
            else {
                state.db = client.db(dbname); // if no error , set state
                cb();
            }
        });
    }
}



module.exports = { connect }; //exposing methods

我是不是哪里弄错了?

mongoDB connection 与从 createConnection

返回的连接不同
  1. .createConnection() returns 连接实例
  2. .connect() returns 全局猫鼬实例

您应该将事件处理程序连接到 createConnection() 返回的连接,而不是 mongoose.connection

或者将您的代码从 'once open' 移到 .connection() 回调函数中。