尝试对MongoDB使用Gridfs时出现“无法读取未定义的属性'一次'”

时间:2019-05-03 13:51:47

标签: node.js mongodb gridfs

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

我在某个地方犯了错误吗?

1 个答案:

答案 0 :(得分:1)

mongoDB 连接与从 createConnection

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

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

或从.connection()回调函数中的“一旦打开”中移动代码。