Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What findOne returns when there is no match?

Tags:

sequelize.js

My nodejs app needs to check if findOne find any match.

  let o = await Model.findOne({where : {name: 'myname'}});
  if (no match in o ) {
  //do something
  } else {
  //do something else
  };

But I did not find any document explaining what findOne returns when there is no match. I know it does not return null or undefined. The return is an object and how I know there is no match.

like image 862
user938363 Avatar asked Nov 06 '18 04:11

user938363


People also ask

What does findOne return if not exists?

If no document satisfies the query, the method returns null.

What does Sequelize findOne return if not exists?

While the findAll() method returns an array even when you have only one matching row, the findOne() method always returns an Object or null when there's no matching row. And that's how the findOne() method works in Sequelize.

What does findOne return MongoDB?

findOne() method returns a Promise that resolves to the first document in the collection that matches the query. If no documents match the specified query, the promise resolves to null .

Which method returns the first document of the match?

The findOne() method finds and returns one document that matches the given selection criteria. If multiple documents satisfy the given query expression, then this method will return the first document according to the natural order which reflects the order of documents on the disk.


1 Answers

Here you go , as per the DOC and below example , it will either return the record or null (for no record found) :

// search for attributes
Project.findOne({ where: {title: 'aProject'} }).then(project => {
  // project will be the first entry of the Projects table with the title 'aProject' || null
})

So in your case , you can do it like :

let o = await Model.findOne({where : {name: 'myname'}});
if (o) {
    // Record Found
} else {
    // Not Found
};
like image 166
Vivek Doshi Avatar answered Oct 19 '22 03:10

Vivek Doshi