0

I have a schema of Delivery:

const DeliverySchema = new mongoose.Schema({
    projectId: { type: String, default: "", trim: true },
    tasks: [{
        timestamp: { type: Date, default: new Date() },
        isAssigned: { type: Boolean, default: false },
        dr1Manager: { type: Schema.Types.ObjectId, ref: 'User' },
        dr2Manager: { type: Schema.Types.ObjectId, ref: 'User' },
        status: { type: String, default: "dr1", trim: true },
        pair: { type: String, default: "", trim: true },
        taskId: { type: String, default: "", trim: true },
        files: [{
            fileName: { type: String, default: "", trim: true },
            path: { type: String, default: "", trim: true },
            isFileApproved: { type: Boolean, default: false },
            isOriginal: { type: Boolean, default: false },
        }],
        instructions: [{
            step: { type: String, default: "dr1", trim: true },
            text: { type: String, default: "", trim: true },
            isChecked: { type: Boolean, default: false }
        }],
    }]
});

I'd like to know if I can $pull data from instructions array and change remaining elements in that array in the same query. I'm trying to do it this way:

await Delivery.updateOne(
  { projectId, "tasks.taskId": taskId },
  {
    "tasks.$[i].isAssigned": false,
    "tasks.$[i].status": "dr1",
    "tasks.$[i].dr1Manager": manager,
    $pull: { "tasks.$[i].instructions": { step: "dr2" } },
    "tasks.$[i].files.$[j].isFileApproved": false,
    "tasks.$[i].instructions.$[k].isChecked": false
  },
  {
    arrayFilters: [
      { "i.taskId": taskId },
      { "j.isFileApproved": true },
      { "k.isChecked": true }
    ]
  }
);

As a result I get an error:

Updating the path \'tasks.$[i].instructions\' would create a conflict at \'tasks.$[i].instructions\

So how can I get that done?

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54

1 Answers1

1

Don't know if that would be suitable, but you can use bulkWrite:

await Delivery.bulkWrite([
  {
    updateOne: {
      filter: { projectId, "tasks.taskId": taskId },
      update: {
        "tasks.$[i].isAssigned": false,
        "tasks.$[i].status": "dr1",
        "tasks.$[i].dr1Manager": manager,
        $pull: { "tasks.$[i].instructions": { step: "dr2" } },
        "tasks.$[i].files.$[j].isFileApproved": false
      },
      arrayFilters: [{ "i.taskId": taskId }, { "j.isFileApproved": true }]
    }
  },
  {
    updateOne: {
      filter: { projectId, "tasks.taskId": taskId },
      update: {
        "tasks.$[i].instructions.$[k].isChecked": false
      },
      arrayFilters: [{ "i.taskId": taskId }, { "k.isChecked": true }]
    }
  }
]);

Here is the docs

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
Daniyal Lukmanov
  • 1,149
  • 10
  • 21