Determine the existence of a document/record in MongoDB

I am having trouble using .find({}) with MongoDB as it is not returning the expected response. I'm not sure how to determine if the document exists or not. What I want to achieve is:

If a document exists, then do something - like sending a response back. But if a document does not exist, then create the document.

However, even though I know the document does not exist, it seems to always trigger 'if (docs)', and when I change it, it keeps creating records?

The code snippet:

addRefund : (refundCalc, callback) => {
    order_number = refundCalc.refundDetails.customer_details.order.order_number;
    dbconnect.createConnection()
    refund.find({order_number: order_number}, (err, docs) => {
        if (docs) {
            console.log('docss!!!!!!!!!!!!!' + JSON.stringify(docs));
            console.log('calling within error!!!!!!')
            let notStored = {"refundDocStored" : "False"}
            callback(notStored)
            dbconnect.closeConnection();
        }
        else {
            refund.create(refundCalc).then((refunddoc) => {
               let filestored = {"refundDocStored" : "True"}                              
               dbconnect.closeConnection();
               callback(filestored)
            }).catch((err)=> {
                console.log(err);
                dbconnect.closeConnection();
            })
        }
    })
},

The schema structure:

const refundSchema = new Schema({
domain : { type: String},
refundDetails : {
    customer_details : [],
    refund : {
        shipping : {
            amount : { type: Number},
            tax : {type : Number},
            maximum_refundable : {type : Number}
        },
        refund_line_items: [],
        transactions: []   
    }
}

The orders are stored within the refundDetails in this format:

"refundDetails":{"customer_details":{"order":{"order_number":1021

It doesn't seem to be working for me! I can't verify if a document actually exists or not.

Any assistance would be appreciated. Thank you!

Answer №1

Your search query is incorrect. You are trying to find the property order_number within an object nested inside another object. To correctly reference the order_number, you should use the full path in your query like this:

{"refundCalc.refundDetails.customer_details.order.order_number" : order_number}

addRefund : (refundCalc, callback) => {
    order_number = refundCalc.refundDetails.customer_details.order.order_number;
    dbconnect.createConnection()
    refund.find({"refundCalc.refundDetails.customer_details.order.order_number": order_number}, (err, docs) => {
        if (docs) {
            console.log('docss!!!!!!!!!!!!!' + JSON.stringify(docs));
            console.log('calling within error!!!!!!')
            let notStored = {"refundDocStored" : "False"}
            callback(notStored)
            dbconnect.closeConnection();
        }
        else {
            refund.create(refundCalc).then((refunddoc) => {
               let filestored = {"refundDocStored" : "True"}                              
               dbconnect.closeConnection();
               callback(filestored)
            }).catch((err)=> {
                console.log(err);
                dbconnect.closeConnection();
            })
        }
    })
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing uploaded files with multer in a Node.js environment using JavaScript

I am facing an issue with uploading multi part form data containing one file input and several text inputs. I have a directory named 'public' which contains a sub-directory named 'uploads'. My goal is to store all multer uploads in the ...

The auto-refresh feature of DataTables is not functioning as expected

Having trouble with the reload feature of DataTables. This is the code I'm using to load and reload the table on the server-side: $( document ).ready(function() { $('#dienst_tabelle').DataTable( { "ajax": "getData ...

Ways to reload a webpage from the bottom without any animation

It seems common knowledge that refreshing a webpage on mobile devices can be done by pulling down from the top. However, I am looking to shake things up and refresh the page by pulling up from the bottom instead. And I prefer no animations in the process. ...

Error message 800A03EA in Windows Script Host encountered while running Express.js script

I'm currently diving into the world of JavaScript development, following along with the guidance provided in the book called "JavaScript Everywhere." The book instructs me to execute the following code: const express = require('express' ...

Attempting to configure Kafka consumer and producer components

Trying to establish a basic producer-consumer flow with Kafka, utilizing node-rdkafka Operating in debug: 'all' mode, the logs display: Producer: test [0]: MessageSet with 1 message(s) delivered Consumer: Fetch topic test [0] at offset 38 (v2) ...

Express server is receiving undefined post parameters from Axios in Vue, even though they are clearly defined in Vue

Within my code, I am utilizing an <img> element as shown below: <img v-bind:word = "thing" @click="action" align="center" src="../assets/pic.png"/> Alongside, there is a method structured in this manner: ...

Determining where to implement the API display logic - on the server side or

Currently, I am in the process of restructuring an API that deals with user profiles stored in one table and profile images in another. The current setup involves querying the profiles table first and then looping through the images table to gather the ass ...

What measures can be taken to ensure that the input checkbox is not toggled by accidentally pressing

There's a checkbox input in a dropdown menu at the top of the page that is giving me some trouble. When I select an option by clicking on it, for some reason pressing the spacebar toggles it off and on. Clicking outside once doesn't correct it, I ...

Server-side Data Fetching with Nuxt.js

Is there a method to exclusively retrieve data from an API on the server-side in NuxtJS due to me needing to include my API_TOKEN in the request headers? Sample Code: <template> <div> <h1>Data obtained using asyncData</h1> ...

Looking for an alternative method since jQuery has deprecated the use of '.toggle()' function

After jQuery deprecated the .toggle() method, I have been searching for a new and simple solution to implement a "Read more" button that slides down a paragraph while changing text to "Read less". Below is the code I have put together: var moreText = "Re ...

How to italicize a portion of output using JavaScript

There are numerous inquiries on the internet and on this site regarding how to make italic fonts, however, none specifically address how to italicize only a section of a string. In my scenario, I have a form where I input the book title, author's nam ...

Organize Javascript objects based on their dates - group them by day, month,

I've scoured the internet for examples but haven't found a suitable one that accomplishes the simple task I need. Maybe you can assist me with it. Here is an array of objects: [ { "date": "2015-01-01T12:00:00.000Z", "photoUrl": "", ...

The React application is showing an empty page without any visible errors during the compilation process

I'm having trouble with my React app - it compiles without errors but only shows a blank page. Can someone help me figure out what's wrong with my code? I'm new to React and could use some guidance. index.js import React from 'react&ap ...

"Vue is throwing an error because it cannot set the property '$offlineStorage' on an undefined object. How can this issue be resolved

While working on my vue ionic app, I integrated the plugin available at https://github.com/filrak/vue-offline. However, upon installing the plugin, an error was encountered: vue-offline.js?bf4e:193 Uncaught TypeError: Cannot set property '$offlineStor ...

Rendering JSON Data in JavaScript using Table Pagination

Currently, I am working on rendering JSON data from a URL onto a table. My challenge is to display only 10 rows per page and I'm seeking guidance on how to achieve this. Below is the code snippet that I am using for rendering the data: const url = " ...

Modifying the input field value in React

I've been attempting to modify the value of an input field after selecting an item from the SelectField in the MaterialUI library. Despite my efforts, I have not yet succeeded. However, based on my research, everything I have written appears to be cor ...

Updated the object in an array retrieved from an API by adding a new key-value pair. Attempted to toggle the key value afterwards, only to find that

Essentially, I am retrieving products from an API and including a new key value isAdded in the object within the products array. I utilized a foreach loop to add that key and it was successfully added. Now, when I click the Add to cart button, the product ...

What is the reason behind the addition of '.txt' by the Next.js `Link` Component when redirecting to `href='/'` on GitHub pages?

My website is hosted on github-pages, and I am using the Link Component from Next.js to navigate within it. However, when I click on a component with the href="/", it adds .txt to the end of the URL. My website follows the /app structure. I have ...

Why is my Laravel function retrieving outdated session data?

Currently, I am in the process of developing a shopping cart feature using session. My goal is to create a function that can update the quantity of an item in the shopping cart and refresh both the subtotal and the list of items in the cart displayed on th ...

I'm confused as to why I keep receiving alert messages every time I click on a button. Can someone please provide

My aim is to enhance the functionality such that clicking the blue button changes the reading status to either <Yes> or <Not>. Any guidance on this would be greatly appreciated. Additionally, I am puzzled as to why, currently, I receive an aler ...