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

我的 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) 行中失败,因为 club 的 _id 是 ObjectId 而 clubs[0] 的 _id 是字符串:


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。有谁知道为什么会这样?


明月笑刀无情
浏览 88回答 1
1回答

弑天下

Mongoose 确实很烦人,因为它处理的是不可变对象。您不能以这种方式直接修改_id。一种解决方案是将 Mongoose 对象转换为常规对象之前:club&nbsp;=&nbsp;club.toObject(); club._id&nbsp;=&nbsp;club._id.toString();如果它不起作用,请尝试深度克隆您的对象。不优雅,但有效:club&nbsp;=&nbsp;JSON.parse(JSON.stringify(club));相关问题:Mongoose 返回的数据是不可变的吗?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript