2015-12-02 83 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 –