Mongoose: ObjectId Comparisons fail inconsistently

前端 未结 2 779
面向向阳花
面向向阳花 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:31

    This goes somewhat beyond the original asked question, but I have found that the .equals method of ObjectID's will return false in some cases where a string comparison will return true even when the values are not null. Example:

    var compare1 = invitationOwningUser.toString() === linkedOwningUser.toString();
    var compare2 = invitationOwningUser.equals(linkedOwningUser);
    var compare3 = String(invitationOwningUser) === String(linkedOwningUser);
    logger.debug("compare1: " + compare1 + "; " + "compare2: " + compare2 + "; " + "compare3: " + compare3);
    

    Output:

    compare1: true; compare2: false; compare3: true 
    

    This occurred when invitationOwningUser (an ObjectID) came from a Collection created using a Mongoose schema, and linkedOwningUser (also an ObjectID) came from a Collection not created using Mongoose (just regular MongoDB methods).

    Here is the document containing invitationOwningUser (the owningUser field):

    {
        "_id" : ObjectId("5782faec1f3b568d58d09518"),
        "owningUser" : ObjectId("5781a5685a06e69b158763ea"),
        "capabilities" : [
            "Read",
            "Update"
        ],
        "redeemed" : true,
        "expiry" : ISODate("2016-07-12T01:45:18.017Z"),
        "__v" : 0
    }
    

    Here is the document containing linkedOwningUser (the owningUser field):

    {
        "_id" : ObjectId("05fb8257c95d538d58be7a89"),
        "linked" : [
            {
                "owningUser" : ObjectId("5781a5685a06e69b158763ea"),
                "capabilities" : [
                    "Read",
                    "Update"
                ]
            }
        ]
    }
    

    So, as a bottom line for me, I'll be using the string comparison technique to compare ObjectID's, not the .equals method.

提交回复
热议问题