如果我拥有属于大集合的以下文档的ID以及 newBusinessId 来更新这些文档。像这样:
const newBusinessId = '8abc4cef176aa342154d00c0'
const paymentsIds = ['5aba5cef176aa342154d2345', '5aba5cef176aa342154d6789']
这些ID属于我的数据库中的以下文档:
[
{
_id: '5aba5cef176aa342154d2345',
state: 'MATURE',
comment: 'some comment 1',
startComment: 'some different comment 1',
expense: 2,
startExpense: 2,
businessId: '5aba5cef176aa342154d9876'
},
{
_id: '5aba5cef176aa342154d6789',
state: 'MATURE',
comment: 'some comment 2',
startComment: 'some comment 2',
expense: 3,
startExpense: 1,
businessId: '5aba5cef176aa342154d5432'
},
]
我想使用相同的 businessId : newBusinessId 更新这些文档,状态值为 INIT 以及使用( startComment,startExpense )的值设置的字段(评论,费用),以便更新后可以得到以下结果:
[
{
_id: '5aba5cef176aa342154d2345',
state: 'INIT',
comment: 'some different comment 1',
startComment: 'some different comment 1',
expense: 2,
startExpense: 2,
businessId: '8abc4cef176aa342154d00c0'
},
{
_id: '5aba5cef176aa342154d6789',
state: 'INIT',
comment: 'some comment 2',
startComment: 'some comment 2',
expense: 1,
startExpense: 1,
businessId: '8abc4cef176aa342154d00c0'
},
]
任何想法如何?我很感激你的努力!
答案 0 :(得分:0)
为了在同一个对象中更新具有另一个字段值的字段(例如,expense = startExpense),你必须迭代,试试这个:
yourModel.find().forEach(
function (elem) {
yourModel.update(
{
_id: { $in: paymentsIds }
},
{
$set: {
state : 'INIT',
comment : elem.startComment,
expense : elem.startExpense,
BusinessId : newBusinessId
}
}
);
}
);