使用node.js和multer在mongodb中使用将多个文件上传到Gridfs

时间:2018-07-19 07:59:13

标签: node.js mongodb express mongoose multer

我的问题是我可以成功地在gridfs中上载多个文件,并使用mongoose.Schema.Types.ObjectId将其中的ID保存在一个模式中,但是问题出在每次创建模式并将其保存到数据库时,我注意到第一个objectId in array是重复的,所以结果是数组的长度是4而不是3,因为我只上传了三个文件,所以如果您要使用db.fs.files.find查看mongodb集合,您将看到上传的文件是3,但在我创建的新闻提要架构中,objectId的长度是4,有时第一个或第二个objectId重复了,我该如何解决此问题?

这是我在NODE.JS服务器中的代码

    //Create a 30 bit names to be saved in mongoDB 
function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  //to generate random letter and numbers
  for (var i = 0; i < 30; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  return text;
}

function disect(returns) {
    return new Promise(resolve => {
        //creating a empty newsfeeds to be used to push a objectId
        newsfeed.create({}, function(err, newfeeds){
            if(err){
                console.log(err);
            } else {
                //loop throught req.files to access it's metadata
                returns.forEach(function(meta) {
                    console.log(meta.originalname);
                    var name = makeid() + '' + meta.size;
                    var filesPath = meta.path;
                    var mimetype = meta.mimetype;

                    //OPEN MONGODB STREAMER
                    Grid.mongo = m0ng00se.mongo;
                    conn.once('open', function(){
                        console.log('-mongoDB connection is now open!-');
                        var gfs = Grid(conn.db);
                        var writestream = gfs.createWriteStream({
                            filename: name,
                            contentType: mimetype
                        })
                        fs.createReadStream(filesPath).pipe(writestream);
                        writestream.on('close', function(filedata) {
                            //create a cloneschema
                            var filemetadata = {
                                    gfs_filename: filedata.filename,
                                    gfs_mimetype: filedata.contentType,
                                    gfs_length: filedata.length,
                                    gfs_chunkSize: filedata.chunkSize
                                }
                            cloneSchema.create(filemetadata, (err, newClone) => {
                                if(err){
                                    console.log(err);
                                } else {
                                    //push the id of created cloneschema to newsfeeds
                                    //and save to mongodb
                                    newfeeds.uploadedmedia.push(newClone._id);
                                    newfeeds.save();
                                    resolve(newfeeds);
                                }
                            })
                        })
                    })
                })
            }
        })
    })
}
//when the first function is done redirect me to homepage
function redirect() {
    new Promise(resolve => {
        res.redirect('/vuyog')
    })
}

async function process(returns) {
    var cons = await disect(returns);
    console.log(cons);
    await redirect();

}
//var metadata = req.files
process(metadata)

这是我终端的输出

`server has started
black t-shirt.png
goldfinchtransparent.png
t-shirt-1278404white.png
-mongoDB connection is now open!-
-mongoDB connection is now open!-
-mongoDB connection is now open!-
{ uploadedmedia: [ 5b503ea241b5fc4e8e757eda ],
  _id: 5b503e9f41b5fc4e8e757ed1,
  __v: 0 }`

这是GRIDFS集合中的输出

`> db.fs.files.find({});
{ "_id" : ObjectId("5b503ea041b5fc4e8e757ed3"), "filename" : "QyHJ4mGXr7fF7EWPlerqFnZiH4uDQM22265", "contentType" : "binary/octet-stream", "length" : 22265, "chunkSize" : 261120, "uploadDate" : ISODate("2018-07-19T07:32:50.305Z"), "aliases" : null, "metadata" : null, "md5" : "310b417278ba624cd2a0b030f7aa40cd" }
{ "_id" : ObjectId("5b503ea041b5fc4e8e757ed2"), "filename" : "BXX411ZOp0L2ghnNHz6CBKTHobdBrE991370", "contentType" : "binary/octet-stream", "length" : 991370, "chunkSize" : 261120, "uploadDate" : ISODate("2018-07-19T07:32:50.623Z"), "aliases" : null, "metadata" : null, "md5" : "9958ea36a1aa14ff106b8eeb080b47bd" }
{ "_id" : ObjectId("5b503ea041b5fc4e8e757ed4"), "filename" : "oqHlwfeux3qgOZUBF5eZe9shIOvC5G1158604", "contentType" : "binary/octet-stream", "length" : 1158604, "chunkSize" : 261120, "uploadDate" : ISODate("2018-07-19T07:32:50.634Z"), "aliases" : null, "metadata" : null, "md5" : "8cbd2f46f78307a7d64a40c0f4c7e626" }`

这是我的NEWSCHEEDS SCHEMA系列中的输出,您将注意到已保存的对象已被复制

` db.newsfeeds.find({});
    { "_id" : ObjectId("5b503e9f41b5fc4e8e757ed1"), "uploadedmedia" : [ ObjectId("5b503ea241b5fc4e8e757eda"), ObjectId("5b503ea241b5fc4e8e757eda"),ObjectId("5b503ea241b5fc4e8e757ee0"), ObjectId("5b503ea241b5fc4e8e757ee1") ], "__v" : 3 }`

有时第二个对象被复制。

0 个答案:

没有答案