5

I am trying to find a way to modify the query results of mongoose.

Below is the self contained model with the post hook

'use strict';

// load the things we need
var mongoose = require('mongoose');
var invoice_db = mongoose.createConnection(config.mongo.url + '/invoiceDB'); //connect to buyer DB
var path = require('path');


// define the schema for our invoice details model
var invoicedetailSchema = new Schema({
    //SCHEMA INFO
});

invoicedetailSchema.post('find', function(results){

console.log('POST FIRED')

    results = results.filter(function(doc){
     return doc.tags.length;
   })
})

var InvoiceModel = invoice_db.model('InvoiceDetail', invoicedetailSchema);


// create the model for seller and expose it to our app
promise.promisifyAll(InvoiceModel);
promise.promisifyAll(InvoiceModel.prototype);
module.exports = InvoiceModel;

The find query is working fine and the post is firing but the results are not filtered per the post hook.

How do i go about editing the results before the results are returned.

Uma Maheshwaraa
  • 563
  • 2
  • 9
  • 17
  • The `filter` function doesn't modify the array it's called on, it returns a _new_ array based on the filtering. But why not exclude the docs with an empty `tags` field in the query instead? See http://stackoverflow.com/questions/14789684/find-mongodb-records-where-array-field-is-not-empty-using-mongoose – JohnnyHK Jul 27 '15 at 16:14
  • @JohnnyHK Ok may be the mechanism to filter is wrong. What I am trying to accomplish is this. In the pre hook I am applying a populate query to mongoose. However some docs don't have any value for population. I would like to filter out anything that doesn't have the populated field. Hope that clarifies a bit – Uma Maheshwaraa Jul 27 '15 at 23:58

0 Answers0