【问题标题】:"Cannot read property 'once' of undefined" when using trying to use gridfs for mongodb尝试将gridfs用于mongodb时,“无法读取未定义的'一次'属性”
【发布时间】:2019-05-03 13:51:47
【问题描述】:

我正在尝试使用 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

我是不是在某个地方弄错了?

【问题讨论】:

    标签: node.js mongodb gridfs


    【解决方案1】:

    mongoDB connection 与 createConnection

    返回的连接不同
    1. .createConnection() 返回一个 Connection 实例
    2. .connect() 返回全局 mongoose 实例

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

    或者将您的代码从 .connection() 回调函数中的“一次打开”中移出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多