Fabrício Lélis Fabrício Lélis - 2 months ago 48
Node.js Question

Mongoose: FindOneAndUpdate() with query from field reference

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

});


These are my entities and I need to find a problem that has a workstation with this address and update the problem status.

How I can do this?

Answer

You can apply match condition without workstation.address to find problem and populate and after that match workstation.address to update status.

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