Mongoose: Find Documents Where a Field Is Not Null or Empty

Updated: December 30, 2023 By: Guest Contributor Post a comment

Overview

This article explores how to retrieve documents from a MongoDB collection using Mongoose, where specific fields are neither null nor empty. Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Handling null or empty fields is a common requirement and Mongoose makes it quite straightforward. By the end of this guide, you will understand how to query for non-null and non-empty fields effectively using several advanced techniques.

Setting the Stage

First, make sure that you have Mongoose installed and connected to your MongoDB. Here’s a snippet to set you up:

import mongoose from 'mongoose';

const connectDb = async () => {
  try {
    await mongoose.connect('mongodb://localhost:27017/myDatabase', {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log('Database connected successfully');
  } catch (err) {
    console.error('Database connection error', err);
  }
};

connectDb();

Assuming our model is named Item, representing items in an inventory:

import { Schema, model } from 'mongoose';

const itemSchema = new Schema({
  name: String,
  description: String,
  price: Number,
  inStock: Boolean
});

const Item = model('Item', itemSchema);

Finding Non-Null and Non-Empty Fields

Let’s begin with basic scenarios and incrementally move to more complex ones.

Basic Non-Null Query

To exclude documents where a specific field, say description, is null, we can do the following:

Item.find({ description: { $ne: null } }, (err, items) => {
  if (err) console.error(err);
  console.log(items);
});

The $ne operator selects the documents where the description field is not equal to null.

Excluding Empty Strings

To find documents where description is neither null nor an empty string:

Item.find({
  description: { $ne: null, $nin: [''] }
}, (err, items) => {
  if (err) console.error(err);
  console.log(items);
});

$nin means “not in,” so this query excludes documents where description is either null or an empty string.

Using Regexp to Filter Out Empty Enumerable Fields

If you have, for instance, an array field and want to ensure that it contains at least one non-empty string, use a regular expression in combination with the $nin operator:

Item.find({
  tags: {
    $ne: null,
    $nin: [[]],
    $regex: /.+/ 
  }
}, (err, items) => {
  if (err) console.error(err);
  console.log(items);
});

In this scenario, tags is an array that should not be null, empty or contain only empty strings.

Advanced Query: Combining Operators

For more complex scenarios, such as when some fields might be null or empty, and you want to ensure at least one is filled, you can combine conditions with logical operators such as $or:

Item.find({
  $or: [
    { 'description': { $ne: null, $nin: [''] } },
    { 'tags': { $ne: null, $nin: [[]], $regex: /.+/ } }
  ]
},
(err, items) => {
  if (err) console.error(err);
  console.log(items);
});

This looks for items with a meaningful description or at least one non-empty string in the tags array.

Null and Empty in Aggregation Pipelines

Moving to aggregation pipelines, you might need to filter out null or empty fields as part of a complex querying operation. Here’s an example using $match:

Item.aggregate([
  {
    $match: {
      description: { $ne: null, $nin: [''] }
    }
  },
  //...other pipeline stages
],
(err, items) => {
  if (err) console.error(err);
  console.log(items);
}
);

Conclusion

In summary, querying non-null and non-empty fields in Mongoose is achieved through the use of Mongoose’s diverse set of query selectors and logical operators. While simple at first, chain multiple conditions to satisfy your data requirements complex multitier queries. Always ensure that such checks are part of your validation strategy to maintain data integrity and easily retrieve meaningful data.

The powerful abilities of Mongoose, combined with the expressiveness of MongoDB’s querying language, make such tasks manageable and efficient, enabling us to build robust and reliable applications. Make sure to refer to the official Mongoose documentation for the most up-to-date information and to explore further capabilities beyond what was covered in this walkthrough.