MongoDB Add a query if property exist

I’m trying to use findOne() with mongoose DB. I’m integrating this with Discord, and I’m checking if the teamName property was provided with one of the options for the Discord command.

Meaning teamName can be undefined or be a string

I came up with this idea of seeing if it’s possible to check if I have the name query be the teamName or be undefined but if the teamName property exist, The team isn’t found.

	const team = await teams.findOne({
				$and: [
					{ [""]: },
					{ division },
					{ name: teamName ? teamName : undefined },

A query is simply a JSON document, or js object if you prefer that terminology.

So, nothing stops you from using if-statements to build it dynamically rather than having a static structure. The structure of the object in your code is static because the field name will always be part of the query.

query = { [""] : , division }
if ( what ever condition you want on teamName )
  // Dynamically update the query object with teamName = teamName
const team = await teams.findOne( query )

Not that I have not used $and because it is not necessary.

See a somewhat related thread How to dynamically add conditions or filters to aggregate query - #2 by steevej.

The course M220JS is full of dynamic queries.