Mongoose:FindOneAndUpdate(),带有来自字段引用的查询

时间:2016-09-22 20:33:37

标签: node.js mongodb mongoose

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

    });

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

我怎么能这样做?

2 个答案:

答案 0 :(得分: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);
        }
      });
    }
  });
});

答案 1 :(得分:0)

在mongoose中,您无法执行多集合请求。

你能做的是:

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

像(例子)

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