0

I am working on e-commerce like app. I have orderItem Schema

const orderItemsSchema = mongoose.Schema(
  {
    order: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'OrderItems',
      required: true,
    },
    product: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Products',
      required: true,
    },
    quantity: {
      type: Number,
      default: 1,
    },
    subCost: {
      type: Number,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

Where product schema has a field "owner" which is also a reference.

I am expecting to get orderItems based on owners of the products.

For Example: A owner want to check which products of him has been sold. So he will query orderItems to get his sold items.

  • You would use the [aggregation framework](https://www.mongodb.com/developer/products/mongodb/introduction-aggregation-framework/) with a [$lookup stage](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/). – Aurast Jan 02 '23 at 17:06
  • Yes, I've tried aggregation and it is working but just curious about if it can be done by find or if I think it should be. – Abdul Quddous Jan 02 '23 at 17:09
  • If you use the aggregation framework to create a view, then you could use `find()` on the view. – Aurast Jan 02 '23 at 17:25
  • Have you any example codes on view? – Abdul Quddous Jan 02 '23 at 17:31
  • There's a lot, just google for "Mongo view". – Aurast Jan 02 '23 at 17:32
  • If you have the _id of the owner, you could get a list of product _id values with find, then you could use populate or aggregation to get the product data. – Joe Jan 02 '23 at 19:37

1 Answers1

0

I'm not an expert in mongoose, so maybe the syntax is not entirely correct:

// You get all products _id that owner currently sells
const yourOwnerObjectId = mongoose.Types.ObjectId(yourOwnerId); // Create the objectId from a string
const productsOwner = Products.find({owner: yourOwnerObjectId}).select({_id: 1})

// You get all orders that contains any of previous product _id
const orderWithProductsSold = OrderItems.find({_id: {$in: productsOwner}})

I'm not sure about what returns the first query regarding _id. Maybe you have to do some type of casting to ObjectId or whatever to perform the second query, but I think the idea is right.

biorubenfs
  • 643
  • 6
  • 15
  • I know it can be done in this way, but this is not the ideal way to use multiple queries. I just want a single query to do this whole thing. – Abdul Quddous Jan 03 '23 at 06:36