0

I have the following test in my Express project:

  it('testing club', async () => {
    let club = await clubDAO.create(baseClubParams);

    console.log(club)
    const resp = await http.put(`/api/user/follow/${club._id}`);
    isOk(resp);
    resp.body.data.clubs.should.include(club);
    console.log(resp.body.data.clubs)

    // Re-fetch user info to verify that the change persisted
    const userResp = await http.get(`/api/user/${currentUser._id}`);
    userResp.body.data.clubs.should.include(clubId);
  });

By the console log, I know that club is:

{
  admins: [],
  _id: 5e8b3bcb1dc53d1191a40611,
  name: 'Club Club',
  facebook_link: 'facebook',
  description: 'This is a club',
  category: 'Computer Science',
  __v: 0
}

and clubs is

[
  {
    admins: [],
    _id: '5e8b3bcb1dc53d1191a40611',
    name: 'Club Club',
    facebook_link: 'facebook',
    description: 'This is a club',
    category: 'Computer Science',
    __v: 0
  }
]

The test fails in the line resp.body.data.clubs.should.include(club) because _id of club is an ObjectId and _id of clubs[0] is a string:

AssertionError: expected [ Array(1) ] to include { admins: [],
  _id: 
   { _bsontype: 'ObjectID',
     id: <Buffer 5e 8b 3b cb 1d c5 3d 11 91 a4 06 11>,
     toHexString: [Function],
     get_inc: [Function],
     getInc: [Function],
     generate: [Function],
     toString: [Function],
     toJSON: [Function],
     equals: [Function: equals],
     getTimestamp: [Function],
     generationTime: 1586183115 },
  name: 'Club Club',
  facebook_link: 'facebook',
  description: 'This is a club',
  category: 'Computer Science',
  __v: 0 }

I try to fix this issue by doing the following:

    let club = await clubDAO.create(baseClubParams);
    club._id = club._id.toString()

    console.log(club)

However, this doesn't change club_id at all. It remains to be an ObjectId. Does anyone know why this is happening?

Pablo
  • 1,302
  • 1
  • 16
  • 35

1 Answers1

0

Mongoose is indeed very irritating because it deals with immutable objects. You can't modify the _id directly this way.

One solution is to transform the Mongoose object to a regular object before :

club = club.toObject();
club._id = club._id.toString();

If it doesn't work, try to deep clone your object. Not elegant, but effective :

club = JSON.parse(JSON.stringify(club));

Related question : is data returned from Mongoose immutable?

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63