2016-09-22 86 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语法和承诺)