簡體   English   中英

將“程序化”數組推送到對象的array屬性

[英]Push “programmatic” array to an Object's array property

我正在構建一個詞庫應用程序,對於這個問題,主要的注意事項是我要為特定的單詞(例如-“貓科動物”,“ tomcat”,“ puss”是“ cat”的同義詞)

我有一個Word對象,帶有一個屬性-“ synonyms”-這是一個數組。 我將向Word同義詞屬性添加一個同義詞數組。 根據此處的MongoDb文檔,唯一將數組的所有索引立即附加到文檔的array屬性的唯一方法是嘗試以下操作:

db.students.update(
   { _id: 5 },
   {
     $push: {
       quizzes: {
          $each: [ { wk: 5, score: 8 }, { wk: 6, score: 7 }, { wk: 7, score: 6 } ],
       }
     }
   }
)

在進一步冒險之前,讓我們重新編寫該解決方案以適合我的數據。

db.words.update(
       { baseWord: 'cat' },
       {
         $push: {
           synonyms: {
              $each: [ { _id: 'someValue', synonym: 'feline' }, { _id: 'someValue', synonym: 'puss' }, { _id: 'someValue', synonym: 'tomcat' } ],
           }
         }
       }
    )

簡潔明了,但不是我要嘗試做的。

如果您事先不知道數據並且想要動態數組,該怎么辦? 我當前的解決方案是拆分數組並運行forEach()循環,從而將數組追加到Word對象的同義詞array屬性中,如下所示:

//req.body.synonym = 'feline,tomcat,puss';
var individualSynonyms = req.body.synonym.split(',');

individualSynonyms.forEach(function(synonym) {

            db.words.update(                                
                { "_id": 5 },                       
                {  $push:  //this is the Word.synonyms
                    {   synonyms: 
                        {   
                        $each:[{ //pushing each synonym as a Synonym object                     
                                uuid : uuid.v4(),                                       
                                synonym:synonym,                                    
                            }]                                  
                        }   
                    }  
                },{ upsert : true },
                function(err, result) {
                    if (err){
                        res.json({  success:false, message:'Error adding base word and synonym, try again or come back later.'  });
                        console.log("Error updating word and synonym document");
                    }
                    //using an 'else' clause here will flag a "multiple header" error due to multiple json messages being returned
                    //because of the forEach loop
                    /*
                    else{                               
                        res.json({  success:true, message:'Word and synonyms added!'    });
                        console.log("Update of Word document successful, check document list");
                    }
                    */             
                }); 
                //if each insert happen, we reach here
                if (!err){
                    res.json({  success:true, message:'Word and synonyms added!.'   });
                    console.log("Update of Word document successful, check document list");
                }       
        });
}           
  • 這可以按預期工作,但是您可能會注意到並在底部發出了注釋,其中注釋了ELSE子句,並檢查了'if(!err)'。 如果執行ELSE子句,我們將收到“多個標頭”錯誤,因為循環會為單個請求導致多個JSON結果。

除此之外,'if(!err)'將引發錯誤,因為它在.update()函數的回調中沒有作用於'err'參數的范圍。 -如果有一種避免使用forEach循環的方法,而是直接將同義詞數組提供給單個update()調用,那么我可以在回調中使用if(!err)。

您可能在想:“只需刪除'if(!err)'子句”,但是僅發送JSON響應而不事先進行最終錯誤檢查(如果是否為if,else,else,if等)似乎是不干凈的。

我在文檔或本網站中找不到這種特殊方法,並且對我來說,這似乎是最佳實踐,因為它可以讓您在發送響應之前執行最終的錯誤檢查。 我很好奇這是否真的可以做到。

我沒有使用控制台,但是在調用每個對象之前,為了方便閱讀,我添加了名稱空間前綴。

不需要“迭代”,因為$each采用“數組”作為參數。 只需.map().split()獲得的數組以及其他數據:

db.words.update(                                
  { "_id": 5 },                       
  {  $push: {
    synonyms: {   
      $each: req.body.synonym.split(',').map(synonym =>
        ({ uuid: uuid.v4, synonym })
      ) 
    }
  }},
  { upsert : true },
  function(err,result) {
    if (!err){
      res.json({  success:true, message:'Word and synonyms added!.'   });
      console.log("Update of Word document successful, check document list");
    }       
  }
);

因此, .split()從字符串中生成一個“數組”,您可以使用.map()將其“轉換”為uuid值的數組,並從.split()的元素中轉換為"synonym" 然后,這是一個直接的“數組”,將與$each一起應用於$push操作。

一個請求。

暫無
暫無

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

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