2015-12-02 139 views
1

有一個MongoDB集合,它是從角度資源返回的對象數組。將新對象插入特定數組索引

[{_id: "565ee3582b8981f015494cef", button: "", reference: "", text: "", title: "", …}, 
{_id: "565ee3582b8981f015494cf0", button: "", reference: "", text: "", title: "", …}] 

我必須允許用戶插入一個對象到數組的任何索引,並通過Mongoose保存到MongoDB。

var object = { 
    button: "", 
    image: {}, 
    reference: "", 
    text: "", 
    title: "", 
}; 

我明白如何將對象推到數組的末尾,但我怎樣才能指定插入的索引?

到目前爲止,思維的第一創建對象:然後使用更新方法來更新陣列中的位置

Slide.create(object, function(result) { 
    console.log(result); 
}); 

回答

1

假設你有以下文件在您的收藏

{ 
     "_id" : ObjectId("565eed81abab97411fbe32fc"), 
     "docs" : [ 
       { 
         "_id" : "565ee3582b8981f015494cef", 
         "button" : "", 
         "reference" : "", 
         "text" : "", 
         "title" : "" 
       }, 
       { 
         "_id" : "565ee3582b8981f015494cf0", 
         "button" : "", 
         "reference" : "", 
         "text" : "", 
         "title" : "" 
       } 
     ] 
} 

您需要使用$position操作數組中指定位置處的$push操作插入元素,如文檔中提到:

要使用$position修改器,它必須與$each修飾符一起出現。

演示

var object = { 
    button: "", 
    image: {}, 
    reference: "", 
    text: "", 
    title: "", 
}; 

db.slide.update({/*filter*/}, 
    { '$push': { 'docs': { '$each': [object], '$position': 1 } } 
}) 

您最近更新的文件將是這樣的:

{ 
     "_id" : ObjectId("565eed81abab97411fbe32fc"), 
     "docs" : [ 
       { 
         "_id" : "565ee3582b8981f015494cef", 
         "button" : "", 
         "reference" : "", 
         "text" : "", 
         "title" : "" 
       }, 
       { 
         "button" : "", 
         "image" : { 

         }, 
         "reference" : "", 
         "text" : "", 
         "title" : "" 
       }, 
       { 
         "_id" : "565ee3582b8981f015494cf0", 
         "button" : "", 
         "reference" : "", 
         "text" : "", 
         "title" : "" 
       } 
     ] 
} 
0
var object = { 
    button: "", 
    image: {}, 
    reference: "", 
    text: "", 
    title: "", 
}; 

arr.splice(2, 0, object); 

將在2nd indexobject陣列中即它將是第三個元素。

+1

我需要更新此對象的MongoDB ......會澄清的問題。 TY –