Mongoose:FindOneAndUpdate()与来自字段引用的查询

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

这些是我的实体,我需要find一个有这个地址的工作站的问题,并更新问题的状态。

我怎么能做到这一点?

您可以应用匹配条件没有workstation.addressfind问题和填充,然后匹配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); } }); } }); }); 

在mongoose,你不能执行多收集请求。

你可以做的是:

  • 查找与问题types/状态相匹配的问题文档
  • 然后检查工作站地址
  • 然后更新状态
  • 然后保存文件

比如(例子)

 // 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语法和Promise)