Home > Software engineering >  Database Query logic
Database Query logic

Time:10-15

I'm making 2 queries to the database. Right now, if even one of them is undefined, I get the generic 'not found' message that is set up. This is because there's an 'else' set up at every DB query where it responds with 'not found' if a value is undefined

What I want to achieve:

If one of them is null, I want to add the value 'nil'. Example:

field1: nil,
field2: 'value'

If both are null, then I want it to respond with the previously mentioned 'not found' message.

What's a good approach for this?

CodePudding user response:

I think your goal may be achieved using 1 call to the database by using https://www.mongodb.com/docs/manual/reference/operator/aggregation/switch/ but please provide example document structure and what the expected behavior should be in a bit more detailed way.

CodePudding user response:

[
  {
    _id: new ObjectId("634989627d163a41b75e1e13"),
    name: 'Ashish Jain',
    address: 'Delhi'
  },
  {
    _id: new ObjectId("634989cc7d163a41b75e1e14"),
    name: '',
    address: 'India'
  },
  {
    _id: new ObjectId("634989cc7d163a41b75e1e15"),
    name: '',
    address: ''
  },
  {
    _id: new ObjectId("634989cc7d163a41b75e1e16"),
    name: 'Ash',
    address: ''
  }
]

This is my existing data in the local database.

Following is my Node.js code:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("test");
  var all_docs = dbo.collection("ccn1").find({}).toArray(function(err, result) {
    if (err) throw err;
    
    
    for (i in result){
        if(result[i]['name'] && result[i]['address']) {
            console.log("name: "   result[i]['name'])
            console.log("address: "   result[i]['address'])
        }

        else if (result[i]['name'] && !result[i]['address']){
            console.log("name: "   result[i]['name'])
            console.log("address: nil")
        }

        else if (!result[i]['name'] && result[i]['address']){
            console.log("name: nil")
            console.log("address: "   result[i]['address'])
        }

        else {
            console.log("Not Found")
        }

        console.log()
        
    }

    db.close();
  });
});

What you are seeing below the output:

(base) ashish@ashishlaptop:~/Desktop/software/node$ node "Hello World Script For MongoDB Local.js" 
name: Ashish Jain
address: Delhi

name: nil
address: India

Not Found

name: Ash
address: nil
  • Related