Skip to content Skip to sidebar Skip to footer

My Api Code Retrieves An Empty Data Array From Mongodb While The Code Works Well On Mongodb Playground

My mongodb database includes a collection of users and each user has an array of shops and each shop has an array of products. Here is a simplified version of my collection structu

Solution 1:

Turns out the casting of the ObjectId seemed to be the issue. We need to use mongoose.Types.ObjectId

The API code will looks like this

getProductByProductId: function (productId) {
returnnew Promise((resolve, reject) => {
  User.aggregate([
  {
  $match: {
    "shops.products._id": mongoose.Types.ObjectId(productId)
  }
  },
  {
    "$unwind": "$shops"
  },
  {
    "$unwind": "$shops.products"
  },
  {
    $match: {
    "shops.products._id": mongoose.Types.ObjectId(productId)
  }
  },
  {
  $project: {
  "_id": "$shops.products._id",
  "title": "$shops.products.title"
  }
}
])
.then(products => {
resolve(products)
}).catch(err => {
reject(err);
});
});
}

Post a Comment for "My Api Code Retrieves An Empty Data Array From Mongodb While The Code Works Well On Mongodb Playground"