Tips for extracting information from MongoDB

As I delve into querying my MongoDB database using Mongoose, I encounter an issue. I am utilizing findOne to search by object_id, with the goal of retrieving the "start" and "end" fields from the corresponding object. However, instead of receiving the expected output, I consistently get 'undefined' logged to the console. Below are the details of my schema, an example object from my Events collection in MongoDB, and the code for my query:

Mongoose Schema:

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var eventSchema = new Schema({
  event: String,
  city: String,
  state: String,
  date: String,
  start: String,
  end: Number,
  radius: String,
  team_1: String,
  team_2: String,
  object_id: String,
  photos: []
})

module.exports = mongoose.model('Event', eventSchema);

Example object from MongoDB Event collection:

{
  "_id": {
    "$oid": "5495d1e2ac1e3caaeee84483"
  },
  "event": "Rockefeller Center",
  "city": "New York",
  "state": "New York",
  "date": "",
  "start": "December 18, 2014",
  "end": "January 2, 2015",
  "radius": "40",
  "team_1": "",
  "team_2": "",
  "object_id": "10881503",
  "photos": []
}

Server code:

//loop through incoming API POSTS. object_id is guaranteed to be in 'data'
req.body.forEach(function (data) {

  var result = Event.findOne(
    {object_id: data.object_id}, 
    { start: 1, end: 1 }
  );

  if (result) {
    var startDate = result.start;
    console.log(startDate);
  } else {
    console.log('object_id not found');
  }
});

Answer №1

When working with MongoDB in Mongoose, the findOne method doesn't directly return the queried document. Instead, it executes a callback function that you specify to handle the result.

req.body.forEach(function (data) {

  Event.findOne(
    {object_id: data.object_id}, 
    { start: 1, end: 1 },
    function(err, result) {
      if (result) {
        var startDate = result.start;
        console.log(startDate);
      } else {
        console.log('object_id not found');
      }
    }
  );

});

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

Is there a way to efficiently display more than 10 data items at a time using the FlatList component in react-native?

Here is the data I am working with: singlePost?.Comments = [ 0: {id: 82, content: "Parent1", responseTo: null} 1: {id: 83, content: "Child1", responseTo: 82} 2: {id: 84, content: "Parent2", response ...

How can you effectively use a table filter extension to sort through dropdown values?

Is there a way to update the dropdown values based on new data after applying the first filter? For example, only displaying $0 in the second dropdown menu? Essentially, I want to filter the values in a table and then have the dropdown options reflect the ...

Problem with Layering in Javascript Canvas Game using Kinetic JS

Currently, I am attempting to replicate the game found at and delving into html5 canvas and kineticJS for my study. Here is the link to my fiddle: http://jsfiddle.net/2WRwY/7/ The issues I am facing are as follows: The tail part of the player in the f ...

Implementing conditional validation in Formik on cancel button click in a React application

When defocusing from the field without entering any data, a validation error occurs. Similarly, if you click on the submit button without giving a value, a validation error is triggered - this behavior is expected. However, how can we prevent the validat ...

Using AngularJs: Invoking Service/Provider in app.config

I need to access my service from within app.config. While searching for a solution, I came across this question, which presented a potential solution that I attempted to implement (not the accepted answer, but the one below with the title "Set up your ser ...

The user model cannot be assigned to the parameter of type Document or null in a mongoose with Typescript environment

While working with Typescript, I encountered an error related to mongoose. The issue arises from the fact that mongoose expects a promise of a mongoose document (in this case, the user's document) or "null" to be resolved during a search operation. Ho ...

Using regex to pick out every instance of zero that comes before a numerical value

I am currently utilizing PowerRename, a tool that allows for regex usage to select portions of filenames for replacement. My goal is to tidy up some filenames by removing the preceding zeroes before a number in the file name (replacing them with nothing). ...

Is there a way for senders to also view their own messages using socket.io?

Using socket.io, I am trying to send a message to a specific user based on their socket.id, and also ensure that the sender can see their own message. The code snippet I am using for this is: socket.to(msg.id).emit('chat message', msg.message);, ...

Is there a way to dynamically create a Vue component for every tier of a nested JSON object without prior knowledge of the total number of tiers available?

I am working with JSON data that includes a list of retailers, some of which have subretailers that go multiple levels deep. My goal is to use Vue to generate markup that will show the parent retailer along with any nested subretailers underneath it, simi ...

Add multiple entries if the key-value pair does not already exist

My current approach involves utilizing insertMany to add documents obtained from the spotify api. The structure of these documents is as follows: { spotify_id: "6400dnyeDyD2mIFHfkwHXN", name: "Pablo Honey", ... } This insertion process is achieved ...

The Battle of Extends and Intersection in Typescript

Typescript's concept of extension is akin to C++'s inheritance. Intersection in Typescript involves creating a new object with all the properties from the intersected classes. Why utilize intersection when extends keyword can already merge ...

Stopping Popups in Chrome When Printing with JavaScript

Javascript function printPage(htmlPageContent) { var newWindow = window.open("about:blank"); newWindow.document.write(htmlPageContent); newWindow.print(); } In this code snippet, we are creating a new window 'newWindow' and then using ...

Learning how to track mouse wheel scrolling using jQuery

Is there a way to track mouse scrolling using jquery or javascript? I want the initial value to be 0 and increment by 1 when scrolling down and decrement by 1 when scrolling up. The value should always be positive. For example, if I scroll down twice, the ...

Having trouble getting autocomplete to work with JQuery UI?

Currently facing issues in implementing the Amazon and Wikipedia Autocomplete API. It seems that a different autocomplete service needs to be used based on the search parameter. Unfortunately, neither of the services work when adding "?search=5" for Wikipe ...

JQuery integration resulting in disappearance of Input-group-btn element

Allow me to explain my current project. I am in the process of developing a Modal that enables users to input a password There will be an option to toggle between showing or hiding the text in the password field using a button positioned on the right sid ...

Tips for creating a window closing event handler in Angular 2

Can someone guide me on how to create a window closing event handler in Angular 2, specifically for closing and not refreshing the page? I am unable to use window.onBeforeunLoad(); method. ...

What could be the reason for my jQuery focusout (or blur) event failing to trigger?

On the jsfiddle link provided, the HTML code at the end section looks like this: <input type="text" id="BLAboxPaymentAmount" value="2"> </br> <input type="text" id="BLAboxSection5Total" value="3"> Below that is the jQuery code snippet: ...

Arranging the data in the table by alternating rows using Datatables

I need to organize my data in a way that includes an additional row for descriptive information, but this particular row should not be sorted. It is crucial for understanding the rest of the data, so hiding or showing it is not an option. Is it possible t ...

Guide on dynamically loading email contacts options in selectize.js

I have been working with selectize.js to create an email contacts feature. However, I am facing an issue where the mail list retrieved from the database is displaying as undefined in selectize. Strangely, when I manually enter the return value, everything ...

The responsiveness of Angular Material appears to be limited when tested in Chrome's debug mode for different devices

I have come across a peculiar issue. Within my HTML file, I have defined two attributes: Hide me on small devices Hide me on larger than small devices When I resize the window, the attributes work as intended. However, when I enter device debug mode ( ...