如何在给定 objectid 的情况下从 mongodb 中的对象数组中检索对象

How to retreive an object from an array of Objects in mongodb given a objectid

我有一组评论,我只想从架构中的一组对象中检索评论。

这是我的架构:

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,
      },
    },
  ],
});

如果 'by' 将是 req.user._id,我如何从数组中获取单个评论。我有以前的代码,但它无法仅检索满足查询的评论。

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.",
    });
  }

这会检索整个卖家文档,但我只想通过给定的 user_id === 检索对象评论:ObjectID

试试看

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

}

尝试将用户 _id 转换为 ObjectId 并将您的条件统一到一个对象中:

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.',
  });
}