Node.js - Aggregate returns object

Asked

Viewed 291 times

0

I am doing locally the Node.js exercise as Mongodb proposed in https://www.w3schools.com/nodejs/nodejs_mongodb_join.asp

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 am getting the following:

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

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

Thank you!

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();
    });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.