The mongoose query appears to be functional in the mongo shell but is experiencing difficulties within a Node.js

Trying to retrieve a list of todos based on the 'userId' associated with each one is proving difficult. The code below does not return any rows:

DB.TodoTable.find({ "userId" : ObjectId("54c12f5f3620c07019e6b144") }, function(err, todos) {
    if (err) return console.error(err);

    console.dir(todos);
})

When examining the mongoose debug output, it shows:

Mongoose: todos.find({ userId: undefined }) { fields: undefined }
[]

Interestingly, when attempting the same query in the mongo shell, it works without issue. Here is an example result from the shell:

> db.todos.find()
{ "_id" : ObjectId("54c12f643620c07019e6b145"), "created_at" : ISODate("2015-01-22T17:12:04.932Z"), "userId" : ObjectId(
"54c12f5f3620c07019e6b144"), "text" : "data", "__v" : 0 }

The database schema looks like this:

var TodoTable = mongoose.model('todos', {
    text : {type : String, default: ''},
    created_at : Date,
    userId : {type:ObjectId, ref:'users'}
});

var UserTable = mongoose.model('users', {
    username: String,
    password: String,
    email: String,
    gender: String,
    address: String
});

Answer №1

It's important to note that while mongoose.Schema.ObjectId may seem like the ObjectID constructor function, it is actually used specifically for defining schemas.

Fortunately, you don't have to manually create an ObjectID from a string when using Mongoose, as it handles this for you based on the schema definition. This means you can simply use:

DB.TodoTable.find({ "userId": "54c12f5f3620c07019e6b144" }, function(err, todos) {...})

If you find yourself in a situation where explicitness is required, you can still access the ObjectID constructor directly:

DB.TodoTable.find({ "userId": mongoose.mongo.ObjectID("54c12f5f3620c07019e6b144") }, 
    function(err, todos) {...})

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

Having difficulty starting 'npm start' in ReactJS

I am a newcomer to ReactJS and the Yeoman generator. I have encountered a problem after generating a project using the following command: npm install -g yo npm install -g generator-react-webpack yo react-webpack After setting up the project name, using ...

Unclear "Issue: NEXUS__UNKNOWN__TYPE has already been declared and imported as a type" error encountered in Nexus GraphQL

I'm encountering an error message while using nexus to define a graphql schema with apollo-server. Error: NEXUS__UNKNOWN__TYPE was already defined and imported as a type The stack trace doesn't provide much insight into where the problem is occ ...

Retrieve Cookie from a designated domain using Express

I am currently working on a React application that communicates with a Node/Express backend. To ensure the validity of requests, I am sending a cookie created by react-cookie from the React app to the Express app. To avoid issues related to naming conflict ...

The nodejs events function is being triggered repeatedly

I have been developing a CMS on nodejs which can be found at this link. I have incorporated some event hooks, such as: mpObj.emit('MP:FOOTER', '<center>MPTEST Plugin loaded successfully.</center>'); Whenever I handle this ...

Searching for requests in parallel to provide a single response using Node.js Express

Looking to fetch data from multiple pages using an API and return an object if a specific value matches. The issue seems to be that the loop is asynchronous, resulting in "not found" being displayed first and then getting a "Cannot set headers after they ...

Best practices for sending an object from client to server using Node.js

What is the best way to transfer a large object from client side to my node.js server? The object is currently stored in a variable within my script tags. ...

Tips for resolving the error message: 'The "path" argument must be a string. Received type undefined' that occurs when executing 'vue add vuetify'

After successfully creating a new app using 'vue create agenda', I proceeded to cd into the project folder and run 'vue add vuetify' to integrate Vuetify. However, I encountered an unexpected error. I attempted to search for solutions ...

Is it possible to implement React Native authentication by utilizing Express sessions?

I currently have a web application that utilizes React on the frontend and Express sessions on the backend for authentication and authorization. I'm interested in exploring if I can apply a similar approach to authenticate mobile users. In my web appl ...

Dealing with HTTP upgrade within ExpressJS: A guide

ExpressJS has made a change where it no longer inherits from http.Server. When attempting to listen on the upgrade event, the server is responding with a 404 Not Found. This is a snippet of the current code: app.on('upgrade', function(req, soc ...

Removing information from a MongoDB database with the help of AngularJS and Node.js

Having trouble deleting data in MongoDB using AngularJS and Node.js, as I keep encountering the error "Cannot DELETE /api/manage-product" in the console. .html file <tbody> <tr ng-repeat="product in vm.result"> ...

Why isn't the router returning JSON data?

Why am I not receiving a response from this code? const express = require('express') const mongoose = require('mongoose') const authRouter = require('./authRouter') //importing the router const PORT = process.env.PORT || 3000 ...

Access your local server from your smartphone by utilizing Express and Node.js to connect to localhost

I am facing an issue where I cannot access the server I host on my computer (using Node.js & Express) from my phone, even though both devices are on the same network. When I type localhost:3000 in the browser on my desktop PC, everything works perfectly f ...

Access to NodeJs localhost:5000 is not successful

Running npm run dev command Issue with accessing localhost - stuck spinning Code snippet: Mycode ...

Error: npm command not recognized in macOS Monterey

The error I'm encountering in macOS M2 is displayed below: https://i.stack.imgur.com/CztMZ.png ...

Navigating through nested routes in Express.js and extracting parameters may seem daunting at first, but

In my routing setup, I have defined it as shown below: export const router = Router(); const appRoutes = [ { path: "/", router: usersRouter, }, { path: "/games/", router: gamesRouter, }, { path: "/gam ...

Encountering difficulty installing a private npm package within GitHub Actions

Having a private npm package within my organization that is crucial for my project, I have encountered an issue while trying to build the project in a different repository. Despite successfully creating tokens and publishing the package from a separate wor ...

Is there a way to verify the presence of a service worker on a specific URL?

Is there a way for me to determine if external websites have a 'service-worker' or not? Here is what I think could work: Extract all the JavaScript files from the given URL Look for the string 'sw.js' (I am not entirely sure how to ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...

What is the quickest method for upgrading node and npm?

Despite my numerous online searches, I am still unable to get it to work. Can someone clarify if my understanding is correct? To upgrade npm to the latest version: npm install npm@latest -g To update node to the latest version: Visit the official webs ...

Is there a way to invoke a different function within a class from a callback function in an HTTP request?

Having an issue with my HTTP GET request function in the "CheckPrice" class. When trying to call another function within the class callback, it's showing as undefined. Any suggestions? const got = require("got") class PriceCheck { constructor() { ...