1

如果我有属于大集合的以下文档的 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 和字段(comment,expense)设置为(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'
  },
]

知道怎么做吗?我很欣赏你的坚强!

4

1 回答 1

0

为了用同一个对象中另一个字段的值更新一个字段(例如费用= startExpense),您必须遍历,试试这个:

yourModel.find().forEach(
    function (elem) {
        yourModel.update(
            {
                _id: { $in: paymentsIds }
            },
            {
                $set: {
                    state : 'INIT',
                    comment : elem.startComment,
                    expense : elem.startExpense,
                    BusinessId : newBusinessId
                }
            }
        );
    }
);
于 2018-03-27T16:29:33.930 回答