我有一个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 }
}],
}]
});
我想知道是否可以从$pull
数组中获取instructions
数据并在同一查询中更改该数组中的其余元素。我正在尝试通过这种方式:
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 }
]
}
);
结果是我得到一个错误:
更新路径\'tasks。$ [i] .instructions \'会产生冲突在\'tasks。$ [i] .instructions \
所以我该怎么做?
不知道这样是否合适,但是您可以使用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 }]
}
}
]);
这里是docs