Node.js - Aggregate object returns

0

I'm locally doing the Node.js exercise as MongoDB proposed at link

There are two collections, orders and product .

After aggregation, the expected result would be:

[
  { _id: 1, product_id: 154, status: 1, orderdetails: [
    { _id: 154, name: 'Chocolate Heaven' } ]
  }
]

However, in my local instance, I'm getting the following:

 [ { _id: 1, product_id: 154, status: 1, orderdetails: [ [Object] ] } ]

Is there any trick for [Object] to be shown as {_id: 154, name: 'Chocolate Heaven'} ?

Thank you!

    
asked by anonymous 09.09.2017 / 02:52

1 answer

0

To show the expected result, you need to use JSON.stringfy ():

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/mydb";

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    db.collection('orders').aggregate([
        {
            $lookup:
            {
                from: 'products',
                localField: 'product_id',
                foreignField: '_id',
                as: 'orderdetails'
            },            
        }
    ], function (err, res) {
        if (err) throw err;
        console.log(JSON.stringify(res));
        db.close();
    });
});
    
09.09.2017 / 23:28