我正在编写一个简单的程序,它将直接从指定的目录处理MP3文件上传进行测试,然后再解析表单数据。现在我遇到了向MongoDB GridFS系统节点驱动程序和节点流API提供适当信息的问题,这将允许我初始化GridFSBucket的实例以开始将文件流式传输到数据库中。 mongo连接从mongoObject.js文件开始,其中插入了一些值以验证数据是否可以流向mLab db,然后该连接将导出整个程序。尝试上传时收到错误
" _chunksCollection: db.collection(options.bucketName + '.chunks'),
TypeError: db.collection is not a function"
感谢您花时间协助,下面是我的代码。
mongoObject.js
var mongodb = require('mongodb'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
// GridStore = require('mongodb').GridStore,
GridFSBucket = require('mongodb').GridFSBucket,
Code = require('mongodb').Code,
// Grid = require('gridfs-stream'),
gridform = require('gridform'),
assert = require('assert'),
mongoURI = 'MLAB-URI-HERE',
test = require('assert');
const dbName = 'crate';
const testUsername = 'user1';
module.exports.startup = function(callback) {
console.log('startup');
MongoClient.connect(mongoURI, function(err, client) {
// Create a collection we want to drop later
const col = client.db(dbName).collection(testUsername);
// Insert a bunch of documents
col.insert([{ a: 31, b: 31 }, { a: 13, b: 13 }], { w: 1 },
function(err, result) {
test.equal(null, err);
console.log("insert");
});
db = client.db(dbName);
});
}
index.js
const { Readable } = require('stream');
var mongodb = require('mongodb'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
// GridStore = require('mongodb').GridStore,
GridFSBucket = require('mongodb').GridFSBucket,
Code = require('mongodb').Code,
// Grid = require('gridfs-stream'),
gridform = require('gridform'),
assert = require('assert'),
mongoURI = 'MLAB-URI-HERE',
test = require('assert');
var db = require('./mongoObject.js');
var ct = './ct.mp3';
function upload(db, ct) {
db = db.client.db(dbName);
console.log("starting bucket");
let bucket = new GridFSBucket({
bucketName: 'user2'
});
const readableTrackStream = new Readable();
readableTrackStream.push(ct);
readableTrackStream.push(null);
let uploadStream = bucket.openUploadStream(ct);
readableTrackStream.pipe(uploadStream)
uploadStream.on('data', (chunk) => {
console.log('data')
})
uploadStream.on('error', (chunk) => {
console.log('err');
})
uploadStream.on('end', () => {
console.log('end');
})
}
upload(db, ct);
package.json依赖项
"dependencies": {
"body-parser": "^1.18.2",
"express": "^4.16.3",
"express-handlebars": "^3.0.0",
"formidable": "^1.2.1",
"gridform": "^0.1.7",
"gridfs": "^1.0.0",
"gridfs-stream": "^1.1.1",
"handlebars": "^4.0.11",
"mongodb": "^3.0.5",
"nodemon": "^1.17.2",
"path": "^0.12.7",
"stream": "0.0.2",
"underscore": "^1.8.3"
}