【发布时间】:2018-01-02 11:27:06
【问题描述】:
我正在尝试使用 mongoosejs 4.9.5 和 mongo 3.2.7 将状态历史记录在子文档数组中
文档结构示例:
-
公司(架构)
- 员工(架构):[ ]i>
- 当前状态:字符串
-
状态(架构):[]
- 状态:字符串
- 开始:日期
- 结束:日期
当我更改员工状态时,我想更改 currentState,将新状态添加到 states 数组中,并更新最后一个状态以定义“结束”时间戳
// I get the last state position from a previous find request
var lastStateIndex = employee.stateHistory.length - 1;
var changeStateDate = new Date();
// Prepare the update
var query = { _id: companyId, "employees._id": employeeId };
var update = {
$set: {
"employees.$.state": newState,
`employees.$.stateHistory.${lastStateIndex}.ends`: changeStateDate
},
$push: {
"employees.$.stateHistory": {
state: newState,
starts: changeStateDate
}
}
}
Company.findOneAndUpdate(query, update, { multi:false, new:true}, ... )
Mongo 返回以下错误
{"name":"MongoError","message":"Cannot update 'employees.0.stateHistory.0.ends' and 'employees.0.stateHistory' at the same time","ok":0,"errmsg":"Cannot update 'employees.0.stateHistory.0.ends' and 'employees.0.stateHistory' at the same time","code":16837}
- 有什么建议可以避免为此目的运行两次更新吗?
- 是否有任何解决方法可以避免存储“结束”日期,但能够在基于数组中下一项的“开始”之后计算它?
谢谢,
【问题讨论】:
-
当然是
"stateHistory"部分。更新语句中的操作应用程序没有“顺序”。所以你不能修改相同的路径。您应该改用.bulkWrite()并在两个单独的操作中在“同一路径”上发出$set和$push。它们需要分开,但“批量”的作用是发送 one 请求和 one 响应,而不是每个响应的“多个”。 -
谢谢尼尔,真的很感激!