MongoDB & Mongoose query returns null for aggregate $or search with non-matching field, returns individual searches or with undefined value omitted

Mikhail

New Member
#1
I'm a bit confused by the behavior I'm seeing in a Mongoose/MongoDB query, as it seems that the $or operator is being treated as an $and
I have the following Collection Document that I am querying for:
Mã:
{
    "_id": {
        "$oid": "5bd0d709ff8eef5d5325090f"
    },
    "audienceTrackingID": "3e66c213-fe0b-4096-a99c-558a6c349b4b",
    "mainframeTrackingID": null,
    "partner1TrackingID": "85c5f168-08da-44d3-bbef-fbb3b8392ded",
    "__v": 0,
    "contentFocus": "Cooking",
    "ipRange": [
        "29.142.127.151"
    ]
}
With the following query:
Mã:
console.log(req.headers['x-original-ip']) // '29.142.127.151'
console.log(req.headers['x-audience-tracking-id']) // undefined
console.log(req.headers['x-partner-1-tracking-id']) // "85c5f168-08da-44d3-bbef-fbb3b8392ded"

const clientMatch = await Client.findOne({
    $or: [{
        ipRange: req.headers['x-original-ip'], 
        audienceTrackingID: req.headers['x-audience-tracking-id'],
        partner1TrackingID: req.headers['x-partner-1-tracking-id'],
    }]
})

console.log(clientMatch) // null
Somewhat puzzling, as querying for individual fields, as well as removing my query where the param is undefined within the actual query (req.headers['x-audience-tracking-id']) will produce results (Which makes me wonder, why is this acting like an AND and giving me null when one queryfield fails???)
Mã:
// ALL QUERIES HIT AND RETURN A MATCH:

const tryThis = await Client.findOne({partner1TrackingID: req.headers['x-partner-1-tracking-id']})
const ipMatch = await Client.findOne({ipRange: req.headers['x-original-ip']})
const clientMatch = await Client.findOne({
    $or: [{
        ipRange: req.headers['x-original-ip'], 
        partner1TrackingID: req.headers['x-partner-1-tracking-id'],
    }]
})
It makes no sense to me. Why would I need to omit a field which may not match from an $or operator in order to get a hit, when other fields match?
 

Admin

Administrator
Thành viên BQT
#2
When you try to run your query you actually get:
Mã:
query failed: cannot compare to undefined
See this here

This is one reason you get no results, another is that your $or query is not correct. You need to separate the or-ed items into separate objects for MongoDB:

So change your code to this:
Mã:
const clientMatch = await Client.findOne({
    $or: [
        {ipRange: req.headers['x-original-ip']}, 
        {audienceTrackingID: req.headers['x-audience-tracking-id'] || ''},
        {partner1TrackingID: req.headers['x-partner-1-tracking-id']},
    ]
})
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top