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.
If no document satisfies the query, the method returns null.
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.
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 .
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.
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With