2016-09-22 12 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

(ここで私はES6構文との約束を使用します)。

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(...)。スナップショット(...)。forEachは関数ではありません。 –

+0

更新された回答を試すことができます@FabrícioLélis –

+0

今、動作します!ありがとう、もう1つの質問です。私は2つ以上の問題があるが、私は1つだけ編集したい。どのようにできるのか? –

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 
    

    は、あなたが問題を発見するためにworkstation.addressずに一致条件を適用し、移入し、その試合workstation.address後のステータスを更新することができます

  • 関連する問題