0

I have the following code:

const Order = require('../../models/order');
const Product = require('../../models/product');

Order.find({}, '_id product quantity', function(err, result) {
  if (result) {
    const response = {
      count: result.length,
      createdOrder: result.map(function(order) {
        return {
          _id: order._id,
          productId: order.product,
          quantity: order.quantity,
          request: {
            type: 'GET',
            url: 'http://localhost:3000/orders/' + order._id
          }
        }
      })
    };
    res.status(200).json(response);
  } else if (err) {
    console.log(err);
    res.status(404).json({
      error: err
    });
  }
});

How to use populate method to give more information about the product in the above syntax?

2 Answers 2

1

In your Order Schema you should set up a ref:

const mongoose = require('mongoose');

const orderSchema = mongoose.Schema({
  // ...,
  product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' }

});

module.exports = mongoose.model('Order', orderSchema);

Populate with product:

Order.find({})
     .populate('product')
     .exec()
     .then(document => {
       // handle the document...
     });

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

1
Order.find({}, '_id product quantity', function (err, result) {

        if (result) {
            const response = {
                count: result.length,
                createdOrder: result.map(function (order) {
                    return {
                        _id: order._id,
                        productId: order.product,
                        quantity: order.quantity,
                        request: {
                            type: 'GET',
                            url: 'http://localhost:3000/orders/' + order._id
                        }
                    }

                })
            };

            res.status(200).json(response);
        }
        else if (err) {
            console.log(err);
            res.status(404).json(
                {
                    error: err
                });
        }
}).populate('product', '_id name price');

The populate method can be used in javascript syntax like the above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.