My findOne() function seems to be malfunctioning - could there be an issue with my syntax?

I have created a database called 'rodrigo-contatos' using the following code:

var mongojs = require('mongojs');
var db = mongojs('rodrigo-contatos', ['rodrigo-contatos']);

In an attempt to search the database, I am using the findOne method from mongojs. Here is the specific code:

app.get('/detalhesContato/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.contatos.findOne({_id: mongojs.ObjectId(id)}, function(err, doc)    {
 console.log(err);
  res.json(doc);

});

Even though console.log(id) shows that the id is correct, the findOne method does not seem to be working as expected.

The following output was logged for the id: "567a16ba28dee028f4a8ad78"

An error occurred: TypeError: Cannot read property 'findOne' of undefined at /Users/Michel/Documents/AngularProjects/RodrigoBranasListaTelefonica/server.js:48:12"

Answer №1

To work with mongojs, you must specify the collections you want to access by defining them as properties of the db object when initializing with mongojs. In this case, if you wish to interact with the contatos collection, you need to provide its name in the array parameter of the mongojs call like so:

var db = mongojs('rodrigo-contatos', ['contatos']);

Alternatively, you can forego direct access through db and retrieve the collection later:

var contatos = db.collection('contatos');
contatos.findOne(...);

Answer №2

Issue resolved by specifying the collection when establishing the database connection. It's interesting that specifying the collection was only necessary for findOne() while find() was functioning properly without it, like so:

var db = mongojs('rodrigo-contatos', ['rodrigo-contatos']); 

However, to work smoothly with findOne(), it should be done like this:

 var db = mongojs('rodrigo-contatos', ['contatos']);

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

Combining MongoDB with the aggregation framework to total the elements within arrays in conjunction with summing up the elements within documents

There are multiple documents containing different data sets: { "_id" : ObjectId("506ddd1900a47d802702a904"), "subid" : "s1", "total" : "300", "details" :[{ name:"d1", value: "100" ...

Unexpected behavior encountered when running Angular 8 radio button checked function

I have an Angular 8 web app with some unique logic implemented as shown below: HTML: <div *ngFor="let item of selectedItems;"> <input type="radio" [(ngModel)]="mySelectedItem" [value]="item.key" (ngModelChange)="setCh ...

Issue with Angular2: The [routerLinkActive] directive does not update when using _router.navigate

My app includes several routerLinks that I have styled using [routerLinkActive]="['active']". Everything works perfectly when I click on one of the routerLinks to navigate. However, when I try to navigate using: this._router.navigate( [ thisUrl ...

I need help setting up XAMPP to install the PHP Mongo driver for PHP version 7.1 and establishing a connection to MongoDB from a PHP script. Can someone provide

I am currently using Windows 10, XAMPP with PHP version 7.1.1, architecture x86, VC14. I have configured my XAMPP to connect to a Mongo database and the MongoDB extension is appearing on my php_info page. However, I am still unable to establish a connectio ...

Unresolved promise rejection on Repl.it

I decided to add a basic leaderboard feature to my game on Repl.it, so I set up a node.js backend for it. Here's the code snippet for the backend: const express = require('express'); const Client = require('@replit/database'); cons ...

Adding new data to an object of objects can be a complex task, especially when the new data is coming from a state variable in React that is also an

I'm currently working on populating an object of objects with new data that is being stored in a state variable in React, which is also an object. Here's the code snippet I have: let userData = { harsh:{ password:"harsh", ema ...

Customizing Axios actions in Vue JS using a variable

I have a form in my Vue component that sends a reservation object to my API for storage. I am exploring the possibility of setting the axios action dynamically based on a variable's value, without duplicating the entire axios function (as both the pos ...

Typescript array iteration using dual parameters

I seem to be struggling with the logic behind this seemingly straightforward iteration question. My task involves iterating through an array of data based on id and code, removing data only when the code is not associated with the given id's. Let&ap ...

Preventing mouse clicks on checkboxes and triggering events using JavaScript - a complete guide

We have a Table grid with multiple columns, one of which is a Select Box (CheckBox). The expected behavior is that when a row is clicked, the respective CheckBox should get checked, and clicking on the CheckBox itself should update it. I tried implementin ...

An odd issue has arisen where the website functions properly in Firefox 3.0 but encounters problems when accessed in Firefox 3

Could someone investigate this issue for me? When you click on the showcase and then on the logo, a modal window should open with the logo. It works perfectly in FF 3.0, but in FF 3.5, the tab switches from showcase to home after clicking the logo. Even ...

What is the method to have the text cursor within a text field start a few pixels in?

I need a text field with the cursor starting a few pixels (let's say 4) from the left-hand side. I am aware that this can be achieved by adjusting the size of the text field using padding, but I am curious if there is a way to resize the text box with ...

Vue - unable to display component CSS classes in application when using class-style bindings

Just diving into Vue and starting with class-style binding syntax. I'm facing an issue where the CSS classes for header and footer that I've defined are not displaying, even though I've referenced them in the component tags. Can't seem ...

Is there a way to confirm the presence of multiple attributes in a JSON format using JavaScript?

Currently, I am developing a module that processes multiple complex JSON files and requires a method to notify users if certain elements are missing. Although the current approach works, I can't shake the feeling that there must be a more efficient a ...

Tips for obtaining response headers

Currently, I am utilizing Angular version 15.0 and retrieving a list of items from the backend (ASP.NET Core 5) with an additional item attached to the header. The GET method in the client-side service is as follows: /** GET Paged commodities from the s ...

Obtaining the outcome of the "dis" distance from a Nearby search

My geo-spacial query is functioning well, but I am interested in determining the distance for each of the results. Using this query: var query = Query.Near("Location", longitude, latitude); var places = mongoDb.GetCollection<Place>("places").Find(n ...

Sending a post request from JavaScript to Django Rest Framework

I am working with a DFR api endpoint: url = http://example.com/api/data/ The URL of the page where I am running JavaScript code is: http://example.com/page/1/ I have logged in as User1 in my browser. POST request - from DRF browser API - successful. G ...

Issues encountered with invoking function in CodeIgniter controller through Ajax

Running a codeigniter website with an add to cart functionality. When the user clicks the add to cart button, the product is successfully added to the cart after the page reloads. The controller code for this feature is as follows: public function buy($ ...

working with JSON array information

I have a JSON array retrieved from a database that I need to manipulate. Currently, it consists of 8 separate elements and I would like to condense it down to just 2 elements while nesting the rest. The current structure of my JSON looks like this: { "i ...

Is there a way to replicate table cells in the style of Excel using jQuery?

Excel has a convenient feature that allows cells to be copied by dragging and dropping with the mouse. This same functionality is also available in Google Spreadsheets. I am trying to understand how Google has implemented this feature using JavaScript cod ...

Is there a way to attach an event for multiple arithmetic operations to a checkbox?

My form includes 4 checkboxes for different mathematical operations. <form action="" method="POST"> Select number of questions: <input type="number" name="que" value="que"> <br> <br> Select number of series: <select name="sel ...