Home > Back-end >  Getting list of users that referenced product model
Getting list of users that referenced product model

Time:09-17

 const productSchema = mongoose.Schema(
    {
      user: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User',
      },
      name: {
        type: String,
        required: true,
      },
      image: {
        type: String,
        required: true,
      },
      price: {
        type: Number,
        required: true,
        default: 0,
      },
    },
    {
      timestamps: true,
    }
  );

const Product = mongoose.model("Product", productSchema);
module.exports = Product;

Hello, Please is it possible to get list or count of users that referenced the product model from the product route or model? i know i get get it through the user route but can i do it from the product route? thanks

CodePudding user response:

Product.aggregate([
  {
    "$lookup": {
      from: "User", /// name of user collection
      "localField": "user",
      "foreignField": "_id",
      "as": "user"
    }
  },
])

this will add user object as user in product doc as array, so you could have all data of user here and list of them

  • Related