0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.