2014년 12월 1일 월요일

MongoDB not throwing error when using find on non-existent collection

When I try to findOne(...) on a non-existent collection MongoDB does not throw an error!

Here is the code I am using:

socket.on('login', function (details) {
        dbHandle
.collection('Users', function(err, logins) {
            
if (err) throw err ;
            logins
.findOne({'user': details.User, 'pwd': details.Pass },function(err, record) {
                
if (err) {
                    console
.log('Oops!') ;
                    socket
.emit('error', { error: 'Oops'} ) ;
                
}
                
else
                
{
// I always get this returned to client!
                    socket
.emit('login', {data: 'record'} ) ;
                
}
            
});
        
}) ;
    
}) ;

I am using MongoDB v2.6.5 on Node.JS v0.10.33 on Linux.

I would appreciate your thoughts on this as I can't see what or where I'm going wrong.



MongoDB creates collections lazily and on-demand, it would be incorrect behaviour to throw an error here, remember MongoDB is not a strict schema database like SQL techs.



Ha hang on you mean on non-existant row not collection



Hi, thanks for the reply.

I am aware of the laziness which is why I was expecting MongoDB to throw an error when it tried to search. But having said that if the collection is then created lazily then there is something to search isn't there!

So apart from my 'record' being null is there any way to determine if a search fails?



I don't believe there is any way to differentiate between a search that doesn't return any results because the collection doesn't exist vs lack of results due to no matches. For most use cases the outcome is semantically equivalent.

If you need certain collections to exist (for example, because they have default data), this sounds like something you probably want to ensure on startup rather than on each request.

You could check a collection exists via collectionNames in the Node driver:



I guess all of that makes sense. I'll have a look at the collectionNames later.


댓글 없음:

댓글 쓰기