2016-03-08 50 views
0

我剛開始學習流星。我把所有的圖像放在「/ public」文件夾的根目錄下。這些圖像被命名爲「1.jpg」,「2.jpg」,「3.jpg」....我想通過使用for循環將所有圖像插入到集合「Images」中,而不將某個數字作爲爲循環限制。那麼我怎樣才能讓它自動檢測公共文件夾中有多少圖片呢?在流星中插入圖片

+0

所以是一個事實,即這些文件圖像的任何相關或可以吧只是被編輯出來?看起來你的問題只是「如何獲得Meteor文件夾中的文件數量」,而且圖像與它無關。 –

+0

是的,我想獲得Meteor文件夾中的「public」文件數量。 –

回答

0

您需要一種機制來獲取公共文件夾中的圖像列表,使用fs包將爲您執行此操作。考慮下面的示例,它使用該包從服務器讀取公共目錄/web.browser/app/(總unix路徑/home/user/your_app_name/.meteor/local/build/programs/web.browser/app/)。

獲取文件夾列表後,名單中篩選與擴展.jpg只得到的圖像文件,然後將圖像到您的收藏。爲了說明目的保存到集合中的圖像文件有以下簡單模式例如

{ _id: "v2PrCTPea6tM6JNHn", name: "1.jpg" } 

當您的圖片插入到蒙戈集合的最終目標幫助你,你可以使用batch-insert流星包,它可以使底層mongo驅動程序插入多個文檔。它的工作原理與insert()類似,但需要插入一組對象而不是一個對象。

#Installation

在您的流星app目錄運行:

meteor add mikowals:batch-insert 

在服務器

var fs = Npm.require('fs'), 
    public_path = path.join(__meteor_bootstrap__.serverDir, "../web.browser/app"), 
    files = fs.readdirSync(public_path), 
    images = _(files).reject(function(fileName) { 
     return fileName.indexOf('.jpg') < 0; 
    }), 
    imagesList = images.map(function (image){ 
     return { name: image }; 
    }); 

Images = new Meteor.Collection('images'); 

Images.allow({ 
    insert: function(){ return true }; 
}); 

var newIds = Images.batchInsert(imagesList); // returns array of created _id values