Mongoose faces difficulty in locating records that were not initially generated using mongoose

After successfully creating a collection and a document in a local running database using mongosh, I encountered an issue while trying to access it via mongoose. Despite querying all documents using a model that matches the collection I created, the document could not be found.

user.js:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/zenwheels', {useNewUrlParser:true, 
useUnifiedTopology: true});

const userSchema = new mongoose.Schema({
    username:{
        type: String,
        required: true
    },
    password:{
        type: String,
        required: true
    }
});

module.exports = mongoose.model('user', userSchema);

admin.js, where I perform the unsuccessful query (only relevant excerpts shown):

const user = require('../models/user');

router.get('/gettest/', async (req, res) =>{

    try{
        const users = await user.find();
        res.json(users);
    }catch(err){
        res.send(500);
    }
})

View of the Database in Compass: https://i.sstatic.net/Flcyf.png

NOTE: Previous attempts included establishing the db connection in admin.js (not shown in my latest attempt mentioned above), but encountered the same issue. Even after referencing the mongoose documentation on document retrieval, the problem persists.

Any assistance would be greatly appreciated.

Answer №1

After creating a test scenario...

app.js

const mongoose = require("mongoose");
const user = require("./models/user");

run().catch(error => console.log(error));

async function run() {
    var uri = "mongodb://barry:barry@localhost:50011,localhost:50012,localhost:50013/nodetest?replicaSet=replSet&authSource=admin";
    const connectionOptions = { useNewUrlParser: true, useUnifiedTopology: true };
    await mongoose.connect(uri, connectionOptions);
    
    await user.create({username: "testuser", password: "testpassword" });
    await getUsers();
}

async function getUsers() {
    try {
        const users = await user.find();
        console.log(users);
    }
    catch (err) {
        console.log(err);
    }
}

./models/user.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema(
    {
        username: { type: String, required: true },
        password: { type: String, required: true }
    },
    {
        collection: "user"
    }
);

const user = mongoose.model('user', userSchema);
module.exports = user;

When running it the first time with no existing data, one record is created and shown...

Running the App

node app.js

Output

[
  {
    _id: new ObjectId("612598d93d79a5db726a348d"),
    username: 'testuser',
    password: 'testpassword',
    __v: 0
  }
]

If a record is manually added to the database using mongoshell...

Manually Added Database Record

Enterprise replSet [primary] nodetest> db.user.insert({username : "manuallycreated", password: "somevalue"})
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("612598ff5e46191be26454b0") }
}

... and the program is run a second time, it displays 3 records, the two created by the program and the manually added one.

%> node app.js
[
  {
    _id: new ObjectId("612598d93d79a5db726a348d"),
    username: 'testuser',
    password: 'testpassword',
    __v: 0
  },
  {
    _id: new ObjectId("612598ff5e46191be26454b0"),
    username: 'manuallycreated',
    password: 'somevalue'
  },
  {
    _id: new ObjectId("61259932f79fa93d54bd8acb"),
    username: 'testuser',
    password: 'testpassword',
    __v: 0
  }
]

Everything appears to be functioning correctly. The manually added record lacks a __v column but is still included in the output...

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

Best practice in AngularJS: Conceal/unveil fresh DOM elements or compile

Just starting out with AngularJS and looking to adjust button behavior on the fly. Coming from a JQuery background, I'm used to using element.attr('ng-click', 'controller.function()'). However, it seems that AngularJS requires co ...

Searching for TypeScript type definitions for the @Angular libraries within Angular 2

After updating my application to Angular2 v2.0.0-rc.1, I am encountering TypeScript compile errors and warnings when webpack bundles my application. These messages appear for any @angular packages referenced in my TypeScript source files: ERROR in ./src/a ...

How can we prevent checkbox and radio buttons from being triggered by accidental taps on the surrounding area on touch-responsive devices?

On touch screen responsive devices, there seems to be an issue where clicking outside the checkbox or radio button (within about 8px) causes the checkbox or radio button to toggle. This problem only occurs on responsive touch devices and works fine on desk ...

Error message in Linux for NodeJS global NPM package: "File or directory does not exist"

After setting up my Ubuntu 14.04 system, I installed nodejs and npm using the command: sudo apt-get install nodejs npm To ensure packages utilize the node interpreter instead of nodejs, I created a symlink with: sudo ln -s /usr/bin/nodejs /usr/local/bin ...

Creating two variables that share an identical name

Can variables with the same name set outside of a function be called within the function? var a = $(window).width(); // This is the variable I want to call if(!$.isFunction(p)){ var a = $(window).height(); // Not this one alert(a); } FIDDLE ...

changing size when hovered over with the mouse is not consistent between entering and exiting

Hi there, I'm currently utilizing the transform: scale(); property on a website and could use some assistance with a particular issue I haven't been able to find an answer for online. Here is the code snippet I'm working with: HTML: <d ...

Is there a way to incorporate vue samples into an independent HTML document?

Striving to broaden my knowledge of Vue, I set out to create a page with tabs inspired by one of the Vue examples available at . However, an obvious error seems to be eluding me, as I encounter a syntax issue on the line import * as Tabs from 'vue-s ...

Error Encountered: AJAX Request Failed with 400 Bad Request

I've been using mithril.js to communicate with my node back-end. I followed the documentation and added an AJAX request, but there seems to be limited information available on mithril. Encountered Error: mithril.js:2130 POST http://localhost:3000/a ...

Dropdown does not populate with data

HTML content <select class="form-control" tabindex="-1" id="superId" name="superId[]" multiple="multiple" required="required" data-bind="options: SupArray, optionsText: ' ...

HTML5 video player with secondary playlist

Looking for a videoplayer setup where there are two playlists, but only one can play at a time. When choosing a video from the first list initially, nothing happens. However, after selecting a video from the second list, the first list starts working. HTM ...

AngularJS: Refresh array following the addition of a new item

After saving an object, I am looking to update an array by replacing the conventional push method with a custom function. However, my attempts have not been successful so far. Are there any suggestions on how to rectify this issue? app.controller("produ ...

Finding the exact location of a specific element within a div: tips and tricks

Is there a way to determine the position of an image inside a div when clicked? Here is my HTML code: <div> <p>test</p> <img src='test1.jpg'/> <p>test</p> <p>test</p> <img src=&ap ...

Issue with jQuery Master-Detail dropdown list selection

Having trouble isolating the code in this jsfiddle script. Despite my efforts, it seems that isolation is not working as expected and Firebug isn't showing any errors on the console: <!DOCTYPE html> <html lang="en"> <head> ...

Exploring the iteration of JSON objects within an array using AngularJS

My auto search module has the following JSON structure. I need to iterate through an array of JSON objects and use keys and values as required. I have attempted the code below. However, with the provided JSON object, I am able to retrieve the key but not ...

How can I apply a class to a list item when clicked using Vue.js and a template component generated by v-for loop?

I'm struggling to add an active class to a list item in a template component when it's clicked, making sure that only one item can have the class at a time. I've attempted different solutions such as passing a new data object on click and r ...

Using the $text operator in MongoDB to search for either a specific phrase or individual word(s)

Currently, I am attempting a comprehensive full-text search that necessitates the use of phrases and/or words. According to the official documentation: If the $search string contains both a specific phrase and individual terms, the text search will only r ...

Using Angular expressions, you can dynamically add strings to HTML based on conditions

I currently have the following piece of code: <div>{{animalType}}</div> This outputs dog. Is there a way to conditionally add an 's' if the value of animalType is anything other than dog? I attempted the following, but it did not ...

Connect-busboy: The file being piped to the write stream is either empty or incorrect, depending on its type

My current project involves testing a file upload feature using connect-busboy. Interestingly, I have encountered a peculiar issue when uploading PNG files - although the file gets uploaded, the content seems to be incorrect and unable to open. Upon furthe ...

Utilizing dynamic routes and incorporating additional search parameters within the URL structure in NextJS has never

Is there a way to use router.push(url); to redirect a user with a URL structure like this: [:lang]/something/[...dynamicRouteParams]?searchParam=true. The problem I'm facing is that the user ends up being redirected to a page with a URL structure lik ...

Creating a file logging system with console.log() in hapi.js

I have recently developed an Application with Hapi.js and have utilized good-file to record logs into a file. However, I am facing an issue where the logs are only written to the file when using request.log() and server.log() methods. My goal is to also lo ...