Yield a mongoose result from a loop in Koa.js

1.2k Views Asked by At

I'm using Koa.js with Mongoose.js. There is a collection in my mongo named css. Which have following schema:

_id
css_name
css_value

I have an array containing a huge list like:

var list = ['font-color', 'back-color', 'font-family', 'back-image', 'back-repeat', ... ];

Now I've declared a mongoose model named css and executing a loop like this:

for(var i = 0; i < list.length; i++) {
   console.log(yield css.findOne({css_name: list[i]}).exec());
}

If I execute the code above it gives null in the console. Whenever I omit the loop, it works perfectly:

//for(var i = 0; i < list.length; i++) {
   console.log(yield css.findOne({css_name: 'font-color'}).exec());
//}

So the problem is with the loop. Can anyone suggest a better working way to fetch all the values from a loop using the mongoose model?

1

There are 1 best solutions below

0
On

I don't really see a problem with your code to be honest, it should work, and if you see null as result is because the query didn't return any document, try mongoose.set('debug', true) and execute the queries yourself. Anyway, if you just need all results at once, just use co-each as follow:

var each = require('co-each')

var styles = ['font-color', 'back-color', 'font-family', 'back-image', 'back-repeat']

// executed in parallel
var results = yield each(styles, function *getStyle(style) {
  return yield css.findOne({ css_name: style }).exec()
})

console.log(results)