简体   繁体   中英

Node.Js - Return 1 if no matching document is found in MongoDB

Following query is written in MongoDB, I want to modify it such that when there is no matching record it should return 1.

Code :

 db.collection("uses").find({users:uid}).toArray((err,response) => {
    if(err){
        throw err;
    }
    if(response){
        res.json(uid);
    }
    else{
        res.json("1");
    }    
})

.find() would return a cursor & since you're using .toArray() on a cursor then it would return an array of objects/documents if any matched or else an empty array, So in your below code adding response.length should work :

 db.collection("uses").find({users:uid}).toArray((err,response) => {
    if(err){
        throw err;
    }
    if(response && response.length){
        res.json(uid);
    }
    else{
        res.json("1");
    }    
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM