我正在尝试使用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
我在某个地方犯了错误吗?
答案 0 :(得分:1)
mongoDB 连接与从 createConnection
返回的连接不同您应该将事件处理程序连接到createConnection()返回的连接上,而不是mongoose.connection
或从.connection()回调函数中的“一旦打开”中移动代码。