How to know when to use db.serialize()?

Question

How to know when to use db.serialize()?

Answer

Oftentimes we will have standalone queries that will only be triggered by a user’s request, for example, a login, the user fills in their info and clicks sign in, that click can trigger a query to search for the user that matches the username and password (hypothetically, passwords should not be stored in databases under no circumstance), if a match is found we let the user go to their profile. but what about when a request is more complicated, for example, if in a movie database a user wants to search for all action movies that have a rating greater than 4 stars, but we have two databases, one is movies, and the second is user ratings, so we would either, nest our query:

db.run("SELECT * FROM Movies ...", (err, rows)=> {
  db.run("SELECT * FROM Ratings WHERE ....", (err, rows) => {
    ...
  })
})

or we could serialize:

db.serialize(() => {
  db.run("SELECT * FROM Movies ...", (err, rows)=> { ... });
  db.run("SELECT * FROM Ratings WHERE ....", (err, rows) => { ... });
})

which we could use to assign the result of one of the queries to a variable and use it for the other.
There will be times when nesting might make more sense, but most commonly, serialize provides great support for multiple queries that either they are dependent of one another, or need to happen in certain order (like a table creation and seeding).

1 Like

In your answer, which clarified, very well, the question asked, you talk about “two Databases”, when, I think, the reference should be “two Tables” in the Database, which is very different.

I am confused about the instruction.

Find a way to wrap the queries in the workspace so that they run synchronously.

But for db.serialize, doesn’t it a way to get things step by step, instead of running together at one time?

synchronously mean running things in a order.

1 Like

Oooh, thanks for your clarification!

1 Like

That’s very interesting what you are saying about login details. How would you normally store user passwords if not in some sort of a database?

1 Like

This is a good question: I am also interested in knowing how passwords are typically stored,
if not in a database.

Could a volunteer provide us with some extra information?
Maybe @coffeencake? Thanks! :v:

Hello, I’m not familiar with the node.js course and I’ve typically worked with credentials stored in a database. However, in one project, we did explore the option of working storing some credentials in local storage.

java - How should an application store its credentials - Information Security Stack Exchange

1 Like