skip to Main Content

I have an array of reviews, I want to retrieve only a review from an array of objects inside a schema.

Here is my schema:

const sellerSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    unique: true,
  },
  reviews: [
    {
      by: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
        unique: true,
      },
      title: {
        type: String,
      },
      message: {
        type: String,
      },
      rating: Number,
      imagesUri: [{ String }],
      timestamp: {
        type: Date,
        default: Date.now,
      },
    },
  ],
});

How can I get a single review from the array if ‘by’ will be req.user._id. I have the previous code, but it is not working to retrieve the review only that satisfies the query.

try {
    const seller_id = mongoose.Types.ObjectId(req.params._id);
    const review = await Seller.findOne(
      { _id: seller_id },
      { reviews: { $elemMatch: { by: req.user._id } } } //get the review that matches to the user_id
    );
    res.status(200).send(review);
  } catch (err) {
    //sends the status code with error code message to the user
    res.status(502).send({
      error: "Error retreiving review.",
    });
  }

This retrieves the whole seller document, but I just want to retrieve the object review with the given a user_id === by: ObjectID

2

Answers


  1. give it a try

    try {
    const seller_id = mongoose.Types.ObjectId(req.params._id);
    const review = await Seller.findOne(
      { _id: seller_id , "reviews.by": req.user._id}, { "reviews.$": 1 }
    );
    res.status(200).send(review);
    

    }

    Login or Signup to reply.
  2. Try to cast also the user _id as ObjectId and unify your conditions into a single object:

    try {
      const seller_id = mongoose.Types.ObjectId(req.params._id);
      const user_id = mongoose.Types.ObjectId(req.user._id);
      const review = await Seller.findOne({
        _id: seller_id,
        reviews: { $elemMatch: { by: user_id } },
      });
      res.status(200).send(review);
    } catch (err) {
      //sends the status code with error code message to the user
      res.status(502).send({
        error: 'Error retreiving review.',
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search