2016-09-22 43 views
0

我收到一個/ r/n終止數據流,我想要插入到mongodb數據庫中。我的mongodb代碼不會插入所有數據

tag~4~keyword~sim 
tag~5~keyword~mib 
tag~4~keyword~gom 
tag~3~keyword~qbo 
tag~6~keyword~qqq 
tag~3~keyword~k94 
tag~4~keyword~g93 

我使用arr.split(〜)把他們分開,所以我會得到其中第一線路將表示爲數組表示如下:

arr[0] refers to tag 
arr[1] refers to 4 
arr[2] refers to keyword 
arr[3] refers to sim 

我想插入它們與該表示的mongodb:

{ 
    tag: 4, 
    keywords: [{ keyword: "sim" }, { keyword: "gom" }, { keyword: "g93"} ] 
} 

我的NodeJS /蒙戈客戶端的要點(天然的)代碼中使用異步如下:

i。檢查集合('dat')是否存在標籤。二,如果標籤不存在,則創建一個文檔並插入標籤號碼
iii。接下來插入keywordObj。

var newTagNumber = parseInt(arr[1]) 
var keywordObj = { keyword: arr[3] }  
async.waterfall([ 
    function(callback) { 
    db.collection('dat') 
      .find({ tag: newTagNumber }, 
      { forceServerObjectId: true}).toArray((err, result) => { 
       db.collection('dat').createIndex({ tag: 1 }, { unique: true }) 
     if (err) return callback(err) 
     if (!result.length) return callback(null, false) 
    }) 
}, 
function(arg1, callback) { 
    if (!arg1) { 
    db.collection('dat') 
      .insertOne({ tag: newTagNumber }, 
       { forceServerObjectId: true }, (err, result2) => { 
     if (err) return callback(err) 
    }) 
    } // end if 

    // insert keyword object into the correct tag 
    db.collection('dat') 
      .updateOne({ tag: newTagNumber }, 
      { $push : { keywords: keywordObj }}, 
      { forceServerObjectId: true }, (err, result3) => { 
      if (err) return callback(err) 
      }) 
    }], 
function(err) { 
    if (err) { 
    if (err.message) { 
     return console.log(err.message) 
    } 
    return console.log(err) 
    } 
}) 

使用標籤4作爲例子,我應該有3關鍵字數組插入關鍵字。但是,我只得到兩個。

我不確定我哪裏出錯了。這可能是由於回調?

+0

我認爲這是問題,我有 - http://stackoverflow.com/questions/17637274/mongodb-doesnt-save-all-data – extensa5620

回答

0

管理搞清楚了!

全部換成了async.waterfall代碼

db.collection('dat') 
    .updateOne({ tag: newTagNumber }, 
      { $push : { keywords: keywordObj }}, 
      { upsert: true }) 
    .then((result) => { 
    console.log('result is ' + result) 
    } 
相關問題