2016-09-22 84 views
1
var WorkstationSchema = new Schema({ 
    tag: { type : String }, 
    address : { type : String , unique : true, required : true }, 
    status: { type : String , required : true }, 
}); 


    var ProblemSchema = new Schema({ 
     type: { type: Number, default: 0 }, 
     status: { type: Number, default: 0 }, 
     dateCreated: { type: String, trim: true, default: '' }, 
     workstation: {type: Schema.ObjectId, ref: 'Workstation'}, 
    }); 

    conditions = {type: problemType, status: 0, 'workstation.address': remote64}; 
    update = {status: 1}; 

    ProblemSchema.findOneAndUpdate(conditions, update, options).populate('workstation', 'address').exec(function (err, problem) { 
      if(err){ 
      //do something 
      } else { 
       console.log(problem); 
       } 

    }); 

這些是我的實體,我需要找到一個問題,該工作站具有此地址並更新問題狀態。貓鼬:FindOneAndUpdate()與來自現場參考的查詢

我該怎麼做?

回答

1

您可以將匹配條件不workstation.address發現問題,並填充和那場比賽workstation.address後更新狀態。

conditions = {type: problemType, status: 0}; 

ProblemSchema.find(conditions).populate("workstation", "address").exec(function(error, docs){ 
    docs.forEach(function (problem) { 
    if(problem.workstation && problem.workstation.address === remote64) { 
     problem.status = 1; 
     problem.save(function(err, doc) { 
     if(err){ 
      //do something 
     } else { 
      console.log(doc); 
     } 
     }); 
    } 
    }); 
}); 
+0

感謝您的幫助,但此解決方案不起作用。因爲forEach不是一個函數。 TypeError:ProblemSchema.find(...)。populate(...)。snapshot(...)。forEach不是函數 –

+0

可以嘗試更新的答案@FabrícioLélis –

+0

現在,它的工作原理!謝謝,但還有一個問題。如果我有兩個以上的問題,但我只想編輯一個。我能怎麼做? –

0

在貓鼬中,您無法執行多集合請求。

你可以做的是:

  • 查找匹配problemType /狀態這個問題的文件
  • 然後檢查工作站地址
  • 然後更新狀態
  • 然後保存文件

類似於(示例)

// Get document that match our requirements 
// And populate the workstation 

ProblemSchema.find({ 
    type: problemType, 
    status: 0, 
}).populate('workstation') 
    .exec() 
    .then((docs = []) => { 
     // Get elements that match the address 
     const matchingElems = docs.filter((x) => x.workstation.address === remote64)); 

     // If no element matching 
     if (!matchingElems.length) return; 

     // Modify all status 
     matchingElems.forEach((x, xi) => (matchingElems[xi].status = 1)); 

     // Then save all documents 
     return this.customFunctionSaveAllDocuments(matchingElems); 
    }) 
    .then(() => ...) // Next code 
    .catch(...); // Handle errors 

(這裏我用ES6語法和承諾)