SwiftDev
SwiftDev

Reputation: 59

How do I check mongodb for empty fields

I am building a react app with no mongoDB and I want to check through a user's collection (Profile) in the database. If any field is an empty string, it should alert the user to complete his/her profile.

How can I get this done please?

Thank you very much.

Upvotes: 0

Views: 869

Answers (1)

Adam Arthur
Adam Arthur

Reputation: 11

Let's assume we have a MongoDB collection that looks like this:

{ "first_name":"Sally", "last_name":"McDaniels", "email":"[email protected]", "username":"sassysally" }

There are several scenarios possible. First, do the fields exist in the collection? In other words, it seems to me we need to check for two conditions:

  1. That an expected field is actually in the document AND
  2. That the fields contains a string with a length > 0

My approach to situations like this is to first write the Mongo Query and test it in the console, and then write the Javascript. Let's start by creating some sample data.

use test-db
db.profiles.insert({
   "first_name":"Sally",
   "last_name":"McDaniels",
   "email":"[email protected]",
   "username":"sassysally"
 });

db.profiles.insert({
   "first_name":"",
   "last_name":"",
   "email":"",
   "username":"anonymous-12345"
 });

db.profiles.insert({
   "first_name":"John",
   "email":"",
   "username":"anonymous-678910"
 });

db.profiles.find({})

This inserts sample records that we can use to test our query against.

First, I need a generic query that will select all records that either have the fields = "" or that do not exist in the record.

db.profiles.find(
  { 
     $or:
       [ 
         { last_name: { $eq: "" } }, 
         { last_name: { $exists: false } } 
       ]
   })

This query will return ALL records where last_name is either "" or does not exist in the database. We repeat this pattern for all fields we want to check.

Finally, we need to constrain the query against a specific user and test against all fields we want confirmed to exist and be non-zero. In this example I'll constrain it by the _id, but you could do it with whatever unique identifier you have for the logged in user.

db.profiles.find({ $and : [
    {"_id" : ObjectId("6381f2c234f9141e153df6f7")},
    { $or:
       [ 
         { first_name: { $eq: "" } }, 
         { first_name: { $exists: false } },
         { last_name: { $eq: "" } }, 
         { last_name: { $exists: false } },
         { email: { $eq: "" } }, 
         { email: { $exists: false } },
         { username: { $eq: "" } }, 
         { username: { $exists: false } },
       ] },
  ]
});

If the query returns a record -- then you know that the profile is incomplete. Now that you have the Mongo Query, in Node.js I would make a function like this:

    async function checkProfileComplete(_id) {
        var query =  
        { 
         $and : 
         [
          {"_id" : mongoose.Types.ObjectId(_id),
           { $or:
            [ 
             { first_name: { $eq: "" } }, 
             { first_name: { $exists: false } },
             { last_name: { $eq: "" } }, 
             { last_name: { $exists: false } },
             { email: { $eq: "" } }, 
             { email: { $exists: false } },
             { username: { $eq: "" } }, 
             { username: { $exists: false } },
            ]
           },
         ]
        };

        // Query the database and put the result into an array
        var profileCompleteAr = await mongoose.connection.db
          .collection("profiles")
          .find(query).toArray();  

        // Check if the array has anything in it.  If it does,
        // it means the profile has missing or incomplete fields.
        if(profileCompleteAr.length > 0){
          return false;
        } else {
          return true;
        }
    }

Please note that the code above is pseudo-code, but this approach should work.

Upvotes: 1

Related Questions