Issues arising when using the "if" statement in mongoose search operations

When I search in MongoDB, I encounter validation issues. If it finds the information I am looking for, it returns the result. However, if it doesn't find anything, it returns an empty document. Here is my code and query in Postman: image

exports.search = (req, res) => {
    // Extract the search string
    var searchString = req.params.search;
    // Find OR
    Document.find({ "$or": [
            { "num_oficio": { "$regex": searchString, "$options": "i"}},
            { "ins_juridico": { "$regex": searchString, "$options": "i"}},
            { "fecha_recepcion": { "$regex": searchString, "$options": "i"}},
            { "remitido": { "$regex": searchString, "$options": "i"}},
            { "origen": { "$regex": searchString, "$options": "i"}},
            { "direccion": { "$regex": searchString, "$options": "i"}},
            { "director": { "$regex": searchString, "$options": "i"}},
            { "asunto": { "$regex": searchString, "$options": "i"}},
            { "estatus": { "$regex": searchString, "$options": "i"}},
            { "observacion": { "$regex": searchString, "$options": "i"}}
    ]}).sort([['fecha_recepcion', 'descending']]).exec((err, document) => {
        if (err) {
            return res.status(500).send({
                status: 'error',
                message: 'Error en la peticion'
            });
        }
        if (!document || document.lenght <= 0) {
            return res.status(404).send({
                status: 'error',
                message: 'No hay documentos relacionados con tu busqueda!'
            });
        }
        return res.status(200).send({
            status: 'success',
            document
        });
    });
}

Answer №1

There is a spelling mistake in your code, lenght should be length:

if (!document || document.lenght <= 0) {

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

Starting with NodeJS: Troubleshooting module not found error

I'm new to NodeJS and I'm following the guide on the official NodeJS site to create a server. I have successfully installed NodeJS on my computer and created an app.js file with the code below: const http = require('http'); const host ...

AngularJS radio buttons are unable to be selected in a simplistic manner

I have implemented a dynamic list display using HTML radio buttons. Here is the code snippet: <html> <head> <script src="angular-v1.5.5.js"></script> </head> <body> <div ng-app="myApp" ng-controller=" ...

Accessing saved images in the client side using nodejs multer

I have successfully implemented file storage in my nodejs application to store images in an uploads folder. It is working well, but now I am facing a challenge when trying to display those images. I have looked at other resources for guidance, but I still ...

Incorporate a minimum height requirement for enabling the scroll to top feature

I am currently dealing with some JavaScript code that scrolls to a specific div when clicked. However, I have encountered an issue where the div is displayed at the very top of the page, causing it to go behind a fixed header that is 90px in height. As a r ...

I am looking to modify a particular value within an array of objects, but for some reason, the update is not being applied correctly

When attempting to copy the array, I update the selected value of a specific object based on the matching memberId. This process works well for a single member, however, issues arise when there are multiple members as the updating doesn't work correct ...

Is the purpose of express.json() to identify the Request Object as a JSON Object?

app.js const express = require('express'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const helloRouter = require('./routes/hello'); const app = express(); app.set(& ...

Server experiencing problem with image uploads

Need Assistance with the Following Issue: Here is the code snippet in ASPX: <input type="Button" id="BtnUpload" class="button1" value="Upload Image" onclick="clickFileUpload();" /> JavaScript function on the ASPX page: function UploadImage(path) ...

What is the best way to include numerous attributes to an element using JavaScript?

Attributes can be included within a string in the following format: let attr = ' min="0" step="5" max="100" '; or let attr = ' min="2019-12-25T19:30" '; and so on. Is there a function available ...

When trying to use routes with the .map() function, it does not seem

I am currently working on developing a multi-page web application using react-router-dom. However, I have encountered an issue with the user list page (userlist.js) where the data inside the .map() function is not being returned. Interestingly, the code pr ...

Developing a personalized data binding feature with AngularJS and utilizing ng-repeat

Looking to design a unique controller that can display multiple similar objects connected to a dataset structured like this: [{name: card1, values: {opt1: 9, opt2: 10}},{name: card1, values: {opt1: 9, opt2: 10}}] The goal is to showcase the name and one ...

Using TypeScript, the fetch function cannot be assigned

Why am I encountering this TS warning? Type 'unknown' is not assignable to type 'PokemonList'.ts(2322) This issue is on line: "return e" Here is the code snippet: export interface PokemonList { count: number; next: stri ...

Discovering XMLHttpRequest Issues within a Chrome Application

Is there a way to identify XMLHttpRequest errors specifically in Chrome App? For instance, I need to be able to recognize when net::ERR_NAME_NOT_RESOLVED occurs in order to display an error message to the user. While XMLHttpRequest.onerror is activated, ...

Using Node-twitter within the Express framework

I'm currently exploring the node-twitter module within the express framework. Although I have a basic understanding of node, including routing, rendering jade templates, and installing packages, I find myself overwhelmed by the sheer number of package ...

How can I move a TableItem from one material UI component to another using drag-and-drop?

I am facing an issue where I need to drag a ListItem from one List component to another. I am uncertain about how to accomplish this in Material UI. ...

Is it possible to deploy Vue.js from a content delivery network (CDN) for production

My decision to use Vue.js for a new project was influenced by its ability to run natively in the browser, unlike React which requires compilation/transpilation via Node. I'm considering linking directly to a CDN like this in my production code: <s ...

Is there a way to prevent this JavaScript code from deleting the initial row of my table?

Looking at the code provided, it's evident that creating and deleting new rows is a straightforward process. However, there seems to be an issue where the default/origin/first row (A-T) gets deleted along with the rest of the rows. The main requiremen ...

Issue encountered when attempting to develop a countdown timer using Typescript

I am currently working on a countdown timer using Typescript that includes setting an alarm. I have managed to receive input from the time attribute, converted it using .getTime(), subtracted the current .getTime(), and displayed the result in the consol ...

Is it possible to create a horizontal navigation bar with buttons that scrolls when media queries are activated? I am looking for a solution using HTML,CSS, JavaScript, and Bootstrap

Struggling to create a horizontally scrollable navigation with buttons for media queries in Bootstrap 5.2, using SCSS for styling. This project is starting to feel overwhelming as we try to replicate the EA site. We're aiming to mimic the behavior of ...

JavaScript error: You are trying to use Array.find() in Redux, but it

I am currently developing a react native application and I am using basic redux for managing the state, although I am a complete beginner to this. In a specific issue, I am facing an issue while fetching data from my redux store in the edit screen where th ...

Locate the parent and child elements within an array

Within the array provided below, there are parent items as well as children. I am currently able to identify parents (depth 0) and their immediate children (depth 1), however I am unsure how to handle deeper nested levels. For reference, you can view the ...