简体   繁体   中英

filter collection based on mongodb query

I have a collection I would like to filter using MongoDB output. My issue is for each request I get a promise pending that cannot be used for filtering. How to resolve all pending promises before moving on ?

My current approach is to use lodash to produce a collection with input as key and MongoDB output as value (approach described here ), merge these two collections by common key (approach described here ) and then filter entries when the new field comment is empty. Currently it does not work because promises are pending during Mongodb request.

Thank you very much for your help.

Note: Connection, Schema and model are already correctly working

import _ from 'lodash'
import Mongoose from 'mongoose';

Mongoose.Promise = global.Promise;

var input = [{'id':'1', 'text':'a'},{'id':'2', 'text':'b'},...]
var ids = _.map(input,'id')
var filtering = _.zipObject(ids, _.map(ids, function(id) {
  var query = Model.find({ id: id }).select({ comment: 1 });
  query.exec();
  return query
}));

// output is currently [{'id':'1','comment':Promise { <pending> },},{'id':'2','comment':Promise { <pending> },},...]
// output should be [{'id':'1','comment':'blabla',},{'id':'2','comment':'',},...]
var output= _({}).merge(_(input).groupBy("id").value(),_(filtering).groupBy("id").value())
  .values()
  .flatten()
  .value();
output = _.filter(output, 'comment')

Mongoose queries respond asynchronously and their responses must be handled accordingly.

Fortunately, query.exec() returns a promise, allowing you to do just that.

var input = [{'id':'1', 'text':'a'}, {'id':'2', 'text':'b'}, ...];
var promises = input.map(function(dataObj) {
    return Model.find({ 'id': dataObj.id }).select({ comment: 1 }).exec()
    .then(function(comment) {
        return { 'id':dataObj.id, 'comment':comment };
    });
});
Promise.all(promises).then(function(results) {
    // do something with `results` (all that lodash stuff)
});

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