将新对象插入特定数组索引

时间:2015-12-02 12:30:09

标签: javascript angularjs mongodb mongoose mongodb-query

有一个MongoDB集合,它是一个从Angular Resource返回的对象数组。

[{_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);
});

然后使用更新方法更新数组中的位置:

2 个答案:

答案 0 :(得分: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" : ""
                }
        ]
}

答案 1 :(得分:0)

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

arr.splice(2, 0, object);

将推送object数组中的2nd index,即它将是第三个元素。