简体   繁体   中英

Mongoose Find Callback Not Executing

I've been slowly converting a callback-heavy module to use promises (Q) and I'm hitting a strange issue with Mongoose Models running find() . In brief, the promise chain was never getting past the initial find command. I've since reverted this method to its callback implementation and am still seeing no callback execution. I've broken it down to its most basic behavior and the handleMedia function is never running.

function getMediaByURL(url) {
  Media.find({url: url}, handleMedia);

  function handleMedia(err, media) {
    console.log(err);
    console.log(media);
  }
}

The DB connection is being created in another module, but I'm seeing all of the right things initialize in the correct order, and the readyState of the Mongoose connection is 1 immediately before the find function is executed. If I convert the find method to a promise using q.nbind as described here and log the value on a 1 second interval, the value is always {state: 'pending') .

I have another model that's saving over the same connection just fine with the promise version of find . I'm at a loss.

you declared "handleMedia function" after "find function" ,so only the callback function is not called.. in your code first find function is executed after that "handleMedia function" is initialized

so try this

function getMediaByURL(url) {
    function handleMedia(err, media) {
        console.log(err);
        console.log(media);
    }
    Media.find({url: url}, handleMedia);
}

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