2013-03-09 49 views
13

看來我不能做一個多重插入流星一樣事情是這樣的MongoDB的文檔中described here ...在Meteor Collection中插入多個文檔是否與純mongodb一樣工作?

在我的js控制檯:

> Test.insert([{name:'hello'},{name:'hello again'}])

它返回

"g3pq8GvWoJiWMcPkC" 

當我去

Test.find().fetch()

我得到如下:

Object 
0: Object 
name: "hello" 
__proto__: Object 
1: Object 
name: "hello again" 
__proto__: Object 
_id: "g3pq8GvWoJiWMcPkC" 
__proto__: Object 

看來流星創建一個超級文件包含兩個我試圖插入作爲單獨的。

有人能告訴我我在做什麼錯嗎?

回答

25

從流星排行榜example code,它看起來像你不能批量插入。您可以使用循環或下劃線迭代函數。

使用下劃線,

var names = [{name:'hello'},{name:'hello again'}] 

_.each(names, function(doc) { 
    Test.insert(doc); 
}) 
+1

謝謝@Prashant這隻作品,這就是我所做的。奇怪的是,批量插入不起作用。 – Mercutionario 2013-03-09 05:27:09

+1

我可以建議你編輯它的'_.each(名稱,函數(doc){ Test.insert(doc); })''因爲否則文檔將嵌套在'name' – Akshat 2013-03-09 07:15:04

+2

我推薦使用[ Array.prototype.forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach),因爲它是_.each()的替代方法。現在Node和許多Web瀏覽器都支持該功能。 – 2014-06-25 22:51:17

3

你應該總是使用bulk insert這些東西。 Meteor不支持開箱即用。 您可以使用batch insert plugin或訪問節點MongoDB的驅動程序本身做到這一點:

var items = [{name:'hello'},{name:'hello again'}], 

    testCollection = new Mongo.Collection("Test"), 
    bulk = testCollection.rawCollection().initializeUnorderedBulkOp(); 

for (var i = 0, len = items.length; i < len; i++) { 
    bulk.insert( items[i]); 
} 

bulk.execute(); 

注意有關MongoDB 2.6+

相關問題