簡體   English   中英

如何在MongoDB對象的每個嵌套數組中添加額外的元素?

[英]How to add an extra element in every nested array of a MongoDB object?

我有一個這樣的MongoDB對象:

[ 
   { poster_ip: '127.0.0.1',
    post_body: 'example',
    _id: 54fc1f7808bac08f6d25f24b,
    __v: 0 },

  { poster_ip: '127.0.0.1',
    post_body: 'example',
    _id: 54fc1f7808bac08f6d25f24a,
    __v: 0 } 
]

我如何才能向每個嵌套數組添加一個額外的元素,所以它將像這樣:

[ 
   { poster_ip: '127.0.0.1',
    post_body: 'example',
    _id: 54fc1f7808bac08f6d25f24a,
    __v: 0,
    newName: NewValue },

  { poster_ip: '127.0.0.1',
    post_body: 'example',
    _id: 54fc1f7808bac08f6d25f24b,
    __v: 0,
    newName: NewValue },
]

我試過了,但是沒有用:

for(var i=0; i<JSONobject.length; i++){
    JSONobject[i].newName= NewValue;
}

我正在使用node.js,該對象是我從mongodb查詢中獲得的結果。

這是函數:

exports.Posts = function(UserID, PostID, callback) {

                Post.find( { post: PostID } , function(err, results) {

                var r = results.toObject(); //here i get error 'has no method toObject'

                for (var i=0; i<r.length; i++){
                    r[i].newName = "NewValue";
                }

                console.log(r);
                    //i don't see any changes here with console.log

                    return callback(null, results);
                });
}

編輯:

經過更多研究后,我發現返回的Mongoose Document不是JSON對象,因此我現在嘗試將其轉換為對象。

我找到答案了!

我們需要通過在查詢鏈中使用lean()來告訴Mongoose,我們所需要的只是返回results的普通JavaScript版本。

這樣,Mongoose跳過了創建完整模型實例的步驟,我們直接獲得了可以修改的results

像這樣:

exports.Posts = function(UserID, PostID, callback) {

                Post.find( { post: PostID } , function(err, results) {


                        for (var i=0; i<results.length; i++){
                            results[i].newName = "NewValue";
                        }

                        console.log(results);

                        return callback(null, results);

                }).lean();
}

我不確定為什么for循環會在這里失敗,因為在我看來這很好。 但是嘗試一下:

results = results.map(function(item) {
    item.newName = "NewValue";
    return item;
});

這將創建一個新數組,其中每個原始項目都將附加新值。

(作為一個經驗法則,使用.forEach() .map() .filter() .reduce() .every().some()幾乎總是優於for一個數組循環時)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM