0

I've been trying to move my data from reward.thisMonth into reward.lastMonth with this query

    await this.userModel.updateMany(
      {},
      {
        $set: {
          'rewards.lastMonth': '$rewards.thisMonth',
          'rewards.thisMonth': { usdt: 0, btc: 0, eth: 0 },
        },
      },
    );

but I got this error :

CastError: Cast to Embedded failed for value "$rewards.thisMonth" at path "lastMonth"

I'm also trying to do with another approach like this

 await this.userModel.updateMany(
      {},
      {
        $set: {
          'rewards.lastMonth': {
            usdt: '$rewards.thisMonth.usdt',
            btc: '$rewards.thisMonth.btc',
            eth: '$rewards.thisMonth.eth',
          },
          'rewards.thisMonth': { usdt: 0, btc: 0, eth: 0 },
        },
      },
    );

and I got this error

CastError: Cast to Number failed for value "$rewards.thisMonth.usdt" at path "usdt"

Both rewards.thisMonth and rewards.lastMonth have same schema structures. How to fix this issue ? I'm using mongodb v4.4.1

Billy Adelphia
  • 1,007
  • 4
  • 19
  • 31
  • you can not access fields value in this approach you need to use [update with aggregation pipeline](https://docs.mongodb.com/manual/tutorial/update-documents-with-aggregation-pipeline/) if you know aggregation pipeline then its would be easy, look at this related [question](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field?rq=1) – turivishal Nov 25 '20 at 04:09
  • @turivishal yes I actually follow that question, my approach is similar. But got casting error on mongoose rather than mongodb itself – Billy Adelphia Nov 25 '20 at 04:15
  • I can not see you have not used that approach, enclose second argument in array [{ $set: ... }]., just read the mongodb documentation, from my first comment. – turivishal Nov 25 '20 at 04:17
  • Wow thanks @turivishal , I just forgot to put the array braces into the code. Thank you for point me into that. – Billy Adelphia Nov 25 '20 at 04:21

0 Answers0