正在从 Javascript 对象重新定义 MongoDB _id 属性

Redefining MongoDB _id attribute from Javascript object

我的 Express 项目中有以下测试:

  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);
  });

通过控制台日志,我知道俱乐部是:

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

俱乐部是

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

resp.body.data.clubs.should.include(club) 行测试失败,因为 _id of club 是一个 ObjectId 而 _id of clubs[0] 是一个字符串:

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 }

我尝试通过执行以下操作来解决此问题:

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

    console.log(club)

然而,这根本没有改变 club_id。它仍然是一个 ObjectId。有谁知道为什么会这样?

Mongoose 确实很烦人,因为它处理的是不可变对象。不能这样直接修改_id。

一种解决方案是在之前将 Mongoose 对象转换为常规对象:

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

如果它不起作用,请尝试深度克隆您的对象。不优雅,但有效:

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

相关问题:is data returned from Mongoose immutable?