Matt
Matt

Reputation: 35261

Mongoose find check null coalesce on nested object in an array

I have a model like this:

var organization = new Schema({
  things:[
    {a:{
      b:string
      }
    }
  ]
})

And I am trying to findOne with Mongoose like this:

let organization = await Organization.findOne({
  "things.a.b": "uniquestring",
});

But the problem is that a may be null.

I would like to do something like this:

let organization = await Organization.findOne({
  "things.a?.b": "uniquestring",
});

Is there a way to check for null on this query?

Upvotes: 0

Views: 211

Answers (1)

Shivam
Shivam

Reputation: 3642

I'm not sure if this answers your question, but can't you do something like this. If you think your only issue is there may be some null objects

Assuming your object looks like this

[
  {
    "things": [
      {
        "a": {
          "b": "test"
        }
      },
      {
        "a": null
      },
      {
        "a": {
          "b": "abc"
        }
      }
    ]
  }
]

Then you can run this query

db.collection.find({
  things: {
    "$elemMatch": {
      "a.b": "test"
    }
  }
},
{
  "things.$": 1
})

You can check MongoDB playground here

Upvotes: 1

Related Questions