Node.js and MongoDB query does not return any results

I'm facing an issue with retrieving data from MongoDB using the find() method. Even though there is data in the collection, I'm getting no results. I'm unable to identify the cause of this problem, can someone assist me?

Here's the expected result: { error: false, message: [ ] }

This project has the following Dependencies:

 "dependencies": {
        "body-parser": "^1.19.0",
        "express": "^4.17.1",
        "express-handlebars": "^3.1.0",
        "mongoose": "^5.8.3",
        "nodemon": "^2.0.2"
   }

server.js

require('./models/db');

const express = require('express');

const loController = require('./controllers/loController');

var app = express();

app.listen(3000, () => {
    console.log('I am Listening ... ');
});

app.use('/lomanager', loController);

db.js

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/LOManager', { useNewUrlParser: true, useUnifiedTopology: true }, (error) => {
    if (!error) console.log('mongoose connection success');
    else console.log("error with mongo connnect" + error);
});

require('./lo.model');

lo.model.js

const mongoose = require('mongoose');

var loSchema = new mongoose.Schema({
    _id: Number,
    name: String,
    email: String
});

module.exports = mongoose.model('LO', loSchema);

loController.js

const express = require('express');
var loSchema = require('../models/lo.model');
var mongoose = require('mongoose');

var router = express.Router();

router.get('/', (req, res) => {
    res.json('hello from lo Controller');
});

router.get('/list', (req, res) => {
    var result = {};
    loSchema.find({}, (err, data) => {
        if (err) {
            result = { "error": true, "message": "error in the find" }
        } else {
            result = { "error": false, "message": data };
        }
        res.json(result);
    });
});

module.exports = router;

Answer №1

the title of your collection is 'LO', therefore make sure to utilize this code

module.exports = mongoose.model('LO', loSchema,'LO');

Answer №2

the reason behind this occurrence is due to Mongoose automatically pluralizing the collection name

therefore, we have another option available:

var loSchema = new mongoose.Schema({
    _id: Number,
    name: String,
    email: String
} , {collection: 'LO'});


module.exports = mongoose.model('LO', loSchema);

this source provides further explanation on this topic!

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

There is no 'Access-Control-Allow-Origin' header found on the requested resource in Node.js

I'm currently facing an issue with basic auth while trying to log in to my Grafana page using Node.js and express. I keep receiving an error message like the one shown below.https://i.stack.imgur.com/vRMOF.png My setup includes 'localhost:4000&a ...

Having trouble executing a custom module on AWS using Node.js, as it keeps exiting with the error message: "Module not found."

I'm encountering an issue when attempting to switch to a fork of the parse-server module on AWS elastic beanstalk. Despite my best efforts, I keep receiving this error upon server startup: Error: Cannot find module 'parse-server' at Fun ...

There seems to be an issue with retrieving data using an Ajax get request in Node.js and Express

I am currently working with an API in JavaScript: router.route('/books') .get(function(req,res){ Repository.getAll().done( function(result){ res.json(result);},function(err){res.send(err);}); }) .post(function(req,res){ ...

Guide on redirecting a React application to the payment success page following the completion of a payment through QR code scanning

I have developed an e-commerce app using PERN (Postgres, Express, React, Node) stack. I am looking to inform users about successful payments by automatically redirecting them to a payment success page after they scan a QR code to make the payment. However ...

Having trouble adding or upgrading packages for your React project?

Struggling with my React project as every time I try to update or install new packages, my computer starts making a lot of noise. It seems to be related to the versions of react-dom and react-router-dom, but I'm unsure how to resolve this without caus ...

The autoincrement feature does not support the schema.path function

Currently, I am facing an issue while attempting to implement an auto-increment ID field for a person collection in a MongoDB cloud database. The error arises at the line containing const schemaKey = this._schema.path(this._options.inc_field); when I inclu ...

A Guide to Effectively Managing Express API Responses in Angular 2

When I make an Express API call from my Angular 2 application, I receive a response in the following way. In my component: this.emailService.sendEmail(this.name, this.email, this.message) .subscribe( (res) => ...

I'm looking for a PHP or Node.js OAuth library specifically for the Bitbucket API. I need to be able to make AJAX calls and interact with the library seamlessly

I am looking for a PHP-based library similar to loginWithBitbucket.php. This library should allow me to send authorization requests, which will trigger the opening of a new tab prompting the BitBucket user to enter their login credentials for authorizati ...

Ember.js: Loading and Playing Audio Files

I've been working on an ember-app that will need to load an audio file during some point in the development process. As I'm also creating a REST-Server using express.js simultaneously, I am trying to figure out the best way to provide the mp3-fil ...

The media type provided is not supported for submitting form data to the spring server

I am facing an issue when trying to upload a file to a remote spring server through an API. Despite converting the data into form data, I keep receiving an unsupported media type error (415). Below is the HTTP post request using express: var FormData = r ...

When working with Express and Axios together, it is important to note that Axios may not handle

I've simplified my use case for testing purposes - clicking a button triggers an UPDATE put request using an axios API. While post, get, and delete requests are functioning correctly, my PUT method consistently returns a 404 Not Found error. It seems ...

"How to retrieve data from a nested object in MongoDB by referencing variables

I am facing an issue with accessing nested objects using a variable in the npm package mongojs. Despite my efforts, the code snippet below is not working as expected: let userID = req.user._id, marketName = req.body.marketName, itemNam ...

What causes the disparity in async.js when it comes to the divergence between waterfall and series/parallelLimit(1)?

This is the initial code that works fine: var fs = require('fs'); var async = require('async'); var addErrParm = function (err, done) {return function(exists) { done(err, exists); }} function testAsync() {var response ...

Utilize the lodash times method for indexing

I have a requirement to duplicate a component "n" number of times. I achieved this by utilizing the lodash method called "times". However, I encountered an issue with assigning an index as a key for the generated components. Below is the snippet of code t ...

Encountering issues with npm-adduser when trying to input credentials for npm account

After developing an npm package on one machine, I cloned it to a different machine and encountered an error when trying to run npm publish: npm ERR! need auth auth and email required for publishing npm ERR! need auth You need to authorize this machine usi ...

Nuxt encountering a critical issue: "module 'dir-glob' not found"

Recently, while running my Nuxt app, I encountered an error after restarting the server using npm run dev. The error message stated that it couldn't find the module 'dir-glob'. Despite finding a similar issue on Stack Overflow related to Ang ...

Ways to Install the ExpressJS Framework

Initially, I have come to realize that starting from version 4 (express), the boilerplate HTML generator has been separated. However, when running the command... npm install -g express-generator ... does this automatically include the core express engine ...

Leveraging TypeORM with MySql in a Node.js Lambda Function

I am currently attempting to create lambda functions in node.js using TypeORM with MySql. Despite installing all the necessary node modules, I encounter errors when deploying the lambda (via serverless) and testing it. The error message is as follows: I am ...

An error is triggered when attempting to use dynamic import within the `module.link()` callback

We have a project that requires the use of vm.Module to execute source code in a custom context. For example, let's consider this source code: import path from 'path'; As per the guidance provided in the Node.js documentation, utilizing a v ...

The issue of overwritten callbacks is occurring due to the use of multiple .use() functions on the

Utilizing a module known as consign, I am able to conveniently include multiple modules from a directory all at once, eliminating the need for numerous require statements. In my code, I have set the mount path for each endpoint at the beginning of the rout ...