0
votes

I'm passing a query that I did in mongoDB to mongoose and it gives me error.

The query in mongo DB is:

db.facturas.find({
    _id: { 
        $in: db.detalles.distinct("id_factura", { 
            category: ObjectId("5889eae21ffcc6da2c6b4ae4")
        })
    }
})

In the APP I build the query like this:

Factura.find({'_id': { "$in" : Detalle.distinct("id_factura",{qrycat}) } })
        .populate('pto_venta')
        .populate('forma_pago')
        .exec(function(err, result) {
          if (err) res.send(err);
          res.json(result); 
        });

And I get the following error in NODEJS:

/var/nodejs/aadides-sgi/node_modules/express/lib/response.js:242 var body = JSON.stringify(val, replacer, spaces); ^

TypeError: Converting circular structure to JSON at Object.stringify (native) at ServerResponse.json (/var/nodejs/aadides-sgi/node_modules/express/lib/response.js:242:19) at ServerResponse.send (/var/nodejs/aadides-sgi/node_modules/express/lib/response.js:151:21) at /var/nodejs/aadides-sgi/app/handlers/facturasHandler.js:494:22 at /var/nodejs/aadides-sgi/node_modules/mongoose/lib/query.js:2176:21 at /var/nodejs/aadides-sgi/node_modules/kareem/index.js:160:11 at Query._find (/var/nodejs/aadides-sgi/node_modules/mongoose/lib/query.js:1019:5) at /var/nodejs/aadides-sgi/node_modules/kareem/index.js:156:8 at /var/nodejs/aadides-sgi/node_modules/kareem/index.js:18:7 at _combinedTickCallback (internal/process/next_tick.js:73:7) at process._tickCallback (internal/process/next_tick.js:104:9) events.js:160 throw er; // Unhandled 'error' event ^

Error: read ECONNRESET at exports._errnoException (util.js:1018:11) at Pipe.onread (net.js:568:26)

1
try ...).populate('forma_pago').lean().exec(...; I guess you are trying to return what the find give to you right through Express, and it do not like to convert the mongoose object into String - Orelsanpls
Does Detalle.distinct("id_factura",{qrycat}) return an Array, because the $in operator selects where a value equals any value in a specified array. e.g. { qty: { $in: [ 5, 15 ] } } - Akinjide
@akinjide No it wouldn't since mongoose operations are asynchronous. - Mikey
What is {qrycat} ? - Mikey

1 Answers

0
votes

Double-check your second argument for distinct() as {qrycat} doesn't look like a valid object.

More importantly, distinct() is asynchronous (like most mongoose operations) so you need have a callback to get the IDs before calling your next operation.

Detalle.distinct("id_factura", {qrycat}, function (err, id_facturas) {
    if (err) 
        return res.send(err);
    // id_facturas should be an array
    Factura.find({'_id': { $in: id_facturas }})
        .populate('pto_venta forma_pago') // Mongoose >= 3.6
        .exec(function(err, result) {
            if (err) 
                return res.send(err); // don't forget the return
            res.json(result); 
        });
});