Mongoose: ObjectId Comparisons fail inconsistently

前端 未结 2 778
面向向阳花
面向向阳花 2020-12-03 06:49

I have a straightforward tool for building collections of documents and then automatically formatting them for EPUB or LaTeX rendering, written on top of ExpressJS. I\'m us

2条回答
  •  半阙折子戏
    2020-12-03 07:18

    A straight == (or ===) comparison will compare the two objects by reference, not value. So that will only evaluate to true if they both reference the very same instance.

    Instead, you should be using the equals method of ObjectID to compare their values:

    story._id.equals(offref.ref)
    

    As @bendytree notes in the comments, if either value could be null (and you want nulls to compare as equal), then you can use the following instead:

    String(story._id) === String(offref.ref)
    

提交回复
热议问题