Mongoose .save恢复原始价值

时间:2017-12-22 05:27:02

标签: javascript mongodb mongoose

我有一个简单的for循环,它只是在Schema中递增一个值。我只需使用文档findOne致电_id。更新文档的属性并调用.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 个答案:

答案 0 :(得分:1)

//试试这个

Class cannot be created (missing no-arg constructor): quickfix.StringField 

//在你的方法中

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)
}

}