Prior to the execution of the .create() function in the JavaScript code, the .find() function is being invoked

I am currently following Colt's Web Dev bootcamp and I have encountered an issue. In his version, everything works perfectly fine but when I use the same code, a new entry is added to the database, however, it is not displayed in the printed items unless I rerun the code.

My question is, why is the .find method running before the .create method and is there a way to prevent this?

This is the JavaScript code snippet:

const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/catapp",
    {
    useNewUrlParser: true,
    useUnifiedTopology: true
    }
)
.then(() => console.log('Connected to DB!'))
.catch(error => console.log(error.message));

let catSchema = new mongoose.Schema({
    name: String,
    age: Number,
    temperament: String
});

let Cat = mongoose.model("Cat", catSchema);

Cat.create ({
    name: "Snow White",
    age: 15,
    temperament: "Bland"
}, function(err, cat){
    if(err){
        console.log("error encountered");
    } else {
        console.log("new cat created")
    }
});

Cat.find({}, function(err, cats){
    if(err){
        console.log("Error encountered");
        console.log(err)
    } else {
        console.log("all cats found")
        console.log(cats);
    }
})

The output in the terminal appears as follows (multiple entries may be present due to repeated program runs):

node cats.js
Connected to DB!
all cats found
[
  {
    _id: 5f4ea2d35e48bb06794bb96f,
    name: 'George',
    age: 11,
    temperament: 'Grouchy',
    __v: 0
  },
  ...
]
new cat created

Answer №1

Generating and locating data asynchronously.

These actions may not always finish in the expected sequence, leading to a situation where the first one to complete determines the result - known as a race condition.

To address this issue, it is essential to ensure that the operations are executed in the correct order.

An easy solution is to place the locate function within the callback of the generate function. This method also prevents unnecessary execution of the locate operation if there are errors during table creation.

There are alternative approaches to handling this situation depending on your specific goals, but exploring topics such as asynchronous JavaScript, callbacks, promises, and avoiding callback hell will help you delve deeper into this area.

Answer №2

Here is an example of how your code could look using async/await syntax:

try {
  await Dog.create ({
    name: "Rex",
    age: 5,
    temperament: "Playful"
  });
  console.log("new dog created");

  const dogs = await Dog.find({});
  console.log("all dogs found")
  console.log(dogs);
} catch(e) {
  console.log("Error occurred");
}

Implementing async/await would address the sequential execution problem.

Answer №3

When using NodeJS, <code>Cat.find
will execute before Cat.create() due to its asynchronous behavior.

To work around this, you have the option of utilizing Cat.find() within the callback function of Cat.create, or implementing a Promise-based approach.

Answer №4

Dog.generate is a synchronous function because it requires instant response, which means that when Dog.generate finishes executing, only then will Dog.fetch begin its execution.

To ensure proper sequence of actions, place the Dog.fetch inside the callback function of Dog.generate within the success condition block.

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

The encoding for double quotation marks vanishes when used in the form action

I am attempting to pass a URL in the following format: my_url = '"query"'; when a user clicks on a form. I have experimented with encodeURI and encodeURIComponent functions as well as using alerts to confirm that I receive either "query" or %2 ...

Integrate JSON data into your JavaScript code using d3.js

Having trouble uploading a .json file to my personal website that is needed to be read by JavaScript code. The goal is to include the data from the .json file in the body of the website. This is the code I am currently using to read and utilize the .json ...

Tips for crafting services using $q and $http requests while avoiding redundancy

Is there an elegant way to write AngularJS services without repetitive $q syntax? I currently write services like this: (function() { function ServiceFactory($q, $timeout, $http) { return { getFoo: function() { va ...

What is the best way to distinguish between my HTML form submission and my JavaScript form modification process?

I am facing a dilemma with the layout of my form and table on the webpage. The structure is as follows: +-------------------------------------------------+ | FORM | | +------------------------------------------- ...

Tips for retrieving the following item in an array using Jquery on a click event

Hey everyone, I'm currently working on changing the HTML content of an object using an array of different HTML elements. However, I've run into some issues with iterating through them properly. I did manage to get it to work once before. EDIT Aft ...

Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this: { "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName" ...

Issue with setTimeout() function not being triggered within a VueJS method

I am currently developing an application that allows a user to reset or shutdown a particular server. I am focused on creating the interface and ensuring that the user receives appropriate messages about the actions being taken. My approach involves displa ...

The prop type for `rows` is invalid in `ForwardRef(DataGrid)`. It was supplied as an object instead of the expected array

Hello there! I'm puzzled as to why my grid table isn't displaying data even though I can confirm that I am receiving data from the API response. I'm wondering what might be wrong with my code. Below is my current code along with the returned ...

Canvas displaying inaccurately (unsteady)

While working on a simple HTML5/javascript game, I encountered an unusual issue with the canvas drawings - they seem to be unstable. I have a map that needs to be drawn in a specific way: The background consists of 2 layers: the ocean and the islands. Th ...

What is the best way to implement target="_blank" in an anchor tag using 'sanitize-html'?

In my current project, I am utilizing the sanitize-html library. Let's say I receive an email containing an anchor tag like this: this is to test something <a href="https://www.google.com/">open google</a> When this email shows up in my ...

Having trouble with the CSS `not` selector?

Below is the code snippet I experimented with XHTML <div> <span>Span1</span> <span>Span12</span> <span>Span13</span> </div> <div> <span>Span1</span> <span> ...

Dealing with Koa-router and handling POST requests

I am facing an issue handling POST requests in my koa-router. Despite using koa-bodyparser, I am unable to receive any data sent through my form. My template engine is Jade. router.js: var jade = require('jade'); var router = require('koa- ...

Is there a specific HTML tag available to instruct the browser to cache my HTML and/or CSS files for future use?

Up to this point, my research has indicated that enabling JavaScript and CSS browser caching typically requires server side settings such as .htaccess. Is there any HTML tag or configuration within the HTML page or JavaScript that can instruct the browse ...

What are the mechanics behind the functionality of ES6 class instance variables?

I'm encountering an issue with the following code that is not behaving as expected: import React, { Component } from 'react'; let result = null; class MyData extends Component { _getData = () => { fetch(url) .then(response = ...

When attempting to use nodejs's collection.find() method with MongoDB, no response is received

I have been struggling to develop a node.js script that can retrieve only the records with a specific string key-value pair from a MongoDB collection containing around 30,000 documents. When I run this query on my MongoDB server, it gives me the exact res ...

Script update addressing CSS application to title attributes to resolve bugs

The following script adds a CSS class to the HTML title attribute. You can find the original page where the script is located here: How to change the style of Title attribute inside the anchor tag? Although it works well, there is a small issue. If the ti ...

React application not displaying element properly?

I am facing an issue with my react modal that displays a sign-in and sign-up form. The problem arises when I try to access the button on the form using its id, which is modal-sign-in-submit-button. document.getElementById('modal-sign-in-submit-button ...

Display sub-objects within Chart.js

I'm currently tackling a project in Ionic 3 where I am utilizing an API that returns a JSON response with nested objects. My goal is to display certain aspects of these objects within a bar graph using chart.js. Unfortunately, I lack experience in ma ...

Is there a way to streamline the process of connecting multiple ajax requests automatically?

After reviewing the lower portion of my function, I realized that I need to repeat info(url_part1 + next + url_part2, function(next) { multiple times. Is there a more efficient way to accomplish this task, perhaps utilizing some type of loop? I have been b ...

The time format you have specified is not supported

Attempting to use the most basic moment test, but encountering issues. The following steps were taken: npm install moment In app.js file, I included the following: var moment = require('moment'); var testDate = new Date(); console.log(moment( ...