1

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

1 Answer 1

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);

}

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

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.