Why upper code run later? (Mongoose, Node.js)

My code:

var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/cat_app");

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

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



//adding a new cat to the database
//*****************Part 01***********************

Cat.create({
	name: "Snow White",
	age: 15,
	temperament: "Bland"
},function(err, cat){
	if(err){
		console.log("There is an error!");
		console.log(err);
	} else{
		console.log("New items added successfully to the database");
		console.log(cat);
	}
});

//retrieve all cats from the DB and console.log each one
//******************Part 02********************

Cat.find({},function(err, cats){
	if(err){
		console.log("SOMETHING WENT WRONG!");
		console.log(err);
	} else{
		console.log("ALL THE CATS!");
		console.log(cats);
	}
});

Before I already created 2 cat(George and Mrs. Norris). Now create a new cat(Snow White).

My output:

root@goorm:/workspace/dataBase# node cats.js
(node:2289) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true
} to MongoClient.connect.
(node:2289) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Mon
itoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
ALL THE CATS!
[
  {
    _id: 5ff3104af3a1bb03c603b041,
    name: 'George',
    age: 11,
    temperament: 'Grouchy',
    __v: 0
  },
  {
    _id: 5ff3129a59df6b06215e4749,
    name: 'Mrs. Norris',
    age: 7,
    temperament: 'Evil',
    __v: 0
  }
]
New items added successfully to the database
{
  _id: 5ff31590d882f808f10cc55a,
  name: 'Snow White',
  age: 15,
  temperament: 'Bland',
  __v: 0
}

My output seems like, it shows Part 02 then Part 01.
What I expect is -

//For Part 01
Snow White

//For Part 02
George
Mrs. Norris
Snow White

Can you please explain why it’s happening?

Hi @Plabon_Kumer_Sarker, I guess it all depends on how these methods were invoked: can you show what cat.js is doing at the moment? :slight_smile:

I assume this functions gets called there.

1 Like

this is cats.js
I tried to copy the code from there.
Try this for a better look.

Is it a challenge/lesson?
If so, which one?
Because if this is all the code you see, there must be something under the hood that is running it for you :slight_smile:

edit: on the other hand, if you are running the code as is, both mongoose methods return Promises, meaning that both function will run and execute the callback of whichever completed first.

If you want to execute in a specific order you need to properly account for asynchronicity.

It’s not a challenge. I am doing a course and I just follow my instructor.
I am using Groom ide.
See this to get my workspace access.
See this to my terminal access.

@Plabon_Kumer_Sarker, I assumed was from one of fcc node/mongo lessons; apologies.

Then it’s just a matter of asynchronicity. See my comment above :slight_smile:
Pretty much both methods return promises, whichever completes first you get the callback first.

You have no guarantee of order unless you properly account for that, for example by calling find only after create is done.

Hope it helps :slight_smile:

1 Like

I don’t understand this :frowning_face:



Ya, I think. Cus database not showing output as a program do.
If I use find (part 02) first and then create Snow white(part 01),
part 02 also showing - snow white!
I also not expect snow white in part 02 portion(“ALL THE CATS!”), cus I didn’t create snow white when I use find!

Mongo, like many other DBs supports atomic transactions. Meaning that it guarantees that a changes takes place “internally” before showing it to the “outside” clients.

In your case we can think of the two requests find and create as coming in simultaneously (this is not a guaranteed tho). Mongo then tries it best to make sure that the changes you are requesting are done before getting back your result.

So that’s why you may see SNOW WHITE already even if find is the “first” operation.

Because you have to understand that there’s no “first” and “second” operations.
But the way you have defined them are two totally parallel operations: “Operation A” and “Operation B”.

This has more to do with network programming and Promises.

The way you structured your code has two distinct operations, each one of them may fail or take a variable amount of time independent from the status of the other.
You made two separate requests: maybe one gets lost, and the other not. Maybe one gets slowed down and the other not.

Hope it makes more sense now.

If you want to find ways to change this behavior I suggest to refresh your knowledge of promises (and maybe use async/await instead of those callbacks) :wink:

Happy coding :sparkles:

2 Likes

@Marmiz Thanks a lot for your informative explanation :heart:
It’s really helpful! :hugs:
Happy Coding :sparkles: