Skip to content Skip to sidebar Skip to footer

Mongoose Not Returning A Record

Well, Last night I posted a question because I was frustrated getting mixed returns on a method call; I got an answer that worked, but I was left confused because it's what I was d

Solution 1:

From your code

module.exports.findKey = function( key, callback ) {

    console.log('--- module.exports.findKey --- ' + key );

    const query = { key: key };
    CouponKey.find(query, callback);

}

The result from function find is always an Array. So if it doesn't have any result it will return an empty array []. Your callback only check if it undefined, I think you should log key value before check to know what you get and check error, too.

CouponKey.findKey( req.params._key, (err, key) => { 
        console.log(err);
        console.log(key);

        if ( key !== undefined ) { // sadly this was working last night - console.log( 'yea ---' + key );

        } else { // now this is all i getconsole.log('ha ha --- ' + req.params._key );

        }

    });

And for mongoose if you want only 1 record you can use function findOne instead of find , it will return an object

About the code blow

const query = { key: key };
x = UserKey.find(query);
console.log(x);

Function find return a mongoose Query not an object from your record. If you need the record, you have to pass a callback or use promise.

Post a Comment for "Mongoose Not Returning A Record"