2017-12-22 12 views
0

私は単純なforループを持っています。これは単にスキーマ内の値をインクリメントしています。私は単に文書_idを使ってfindOneと呼んでいます。 Docのプロパティを更新し、.saveを呼び出します。しかし、私はそれが増分したことがない気付いています、それだけで0に戻り、その値が マングース。元の値に戻すことを保存する

検索/更新コード

1.上記
try { 
    for(let i = 0; i < 6; i++) { 
    const find = async() => { 
     const found = await JobStatus.findOne({_id: mongoose.Types.ObjectId(data._id)}) 
     .exec().then(function(doc) { 
      console.log("Before "+i+" : " +doc.number_of_items_processed) 
      doc.number_of_items_processed += 1 
      doc.save(); 
     console.log("After "+i+" : " +doc.number_of_items_processed) 
     }) 
    } 
    find() 
    }//for(....) 
} catch (err) { 
    console.log(err) 
} 

を行くことはありませんこれは、コンソール出力です:

Before 0 : 0 
After 0 : 1 
Before 2 : 0 
After 2 : 1 
Before 1 : 0 
After 1 : 1 
Before 3 : 0 
After 3 : 1 
Before 5 : 0 
After 5 : 1 
Before 4 : 0 
After 4 : 1 

db.jobstatuses.find().pretty() 
{ 
     "_id" : ObjectId("5a3c981cbd8f4128c48d8207"), 
     "number_of_items_submitted" : 5059, 
     "number_of_items_processed" : 1,//STARTS OUT WITH 0 
     "time_completed" : null, 
     "job_outcome" : "Submitted", 
     "job_errors" : null, 
     "time_submitted" : ISODate("2017-12-22T05:29:00.530Z"), 
     "__v" : 0 
} 

答えて

1

//この

try { 
    for(let i = 0; i < 6; i++) { 
    const find = async() => { 
     const found = await JobStatus.update({_id: mongoose.Types.ObjectId(data._id)},{$inc:{number_of_items_processed:1}}) 
     .exec().then(function(doc) { 
      console.log("Number of items processed"+ doc.number_of_items_processed); 
     }) 
    } 
    find() 
    }//for(....) 
} catch (err) { 
    console.log(err) 
} 

//あなたのアプローチで試してみてください

try{ 
    for(let i = 0; i < 6; i++) { 
    const find = async() => { 
    const found = await JobStatus.findOne({_id: mongoose.Types.ObjectId(data._id)}).exec();  
     console.log("Before "+i+" : " +found.number_of_items_processed) 
     found.number_of_items_processed += 1 
     found.save(); 
     console.log("After "+i+" : " +found.number_of_items_processed) 
    } 
    find() 
    }//for(....) 
    } catch (err) { 
    console.log(err) 

}

+0

ありがとうございました。この作業は私のアプローチに間違いがあるのか​​不思議です。 –

+0

非同期問題があなたのアプローチにあります –

+0

申し訳ありません私はビジー..i私のコードを修正し、あなたのアプローチで何が問題であるかを見つけるでしょう。 –

関連する問題