0

I am learning mongoose and I'm unable to understand some code execution order of javascript

Code:


    const mongoose = require("mongoose");

    mongoose.connect("mongodb://localhost:27017/fruitsDB");

    const fruitSchema = new mongoose.Schema({
      name: {
        type: String,
        required: [true, "Please check your data entry, no name specified!"],
      },
      rating: {
        type: Number,
        min: 1,
        max: 10,
      },
      review: String,
    });

    const Fruit = mongoose.model("Fruit", fruitSchema);

    // Reading data from database
    Fruit.find((err, fruits) => {
      if (err) {
        console.log(err);
      } else {
        // console.log(fruits);
        mongoose.connection.close();
        fruits.forEach((fruit) => {
          console.log(fruit.name);
        });
      }
    });

    // Updating data in database
    Fruit.updateOne({ name: "Kiwi" }, { name: "Peach" }, (err) => {
        if (err) {
            console.log(err);
        }
        else {
            console.log("Successfully updated data");
        }
    });

    // Deleting data in database
    Fruit.deleteOne({ name: 'Peach' }, (err) => {
        if (err) {
            console.log(err);
        }
        else {
            console.log('Data deleted successfully');
        }
    })

console.log output: console.log output

I am unable to understand why the Update function in running before the find() function, can anyone explain this to me please?

rickhg12hs
  • 10,638
  • 6
  • 24
  • 42
  • this likely has to do with the Async nature of Javascript. It's especially "complicated" when working with APIs, date etc. "Javascript Async" is going to get your brain smoking :) – Frizzant Sep 05 '22 at 14:21
  • You will need to wait for the find function results – Lk77 Sep 05 '22 at 14:24
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ivar Sep 05 '22 at 14:25
  • "_I am unable to understand why the Update function in running before the find() function_" - It doesn't. The function you you pass _as a callback function_ to the `.find()` method is executed after the function you pass as a callback function to the `.updateOne()` function. The whole purpose of them being callback functions, is because they don't happen immediately, but only after they have a response from the database. The rest of the code wont wait for that. – Ivar Sep 05 '22 at 14:27

0 Answers0