最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

使用mongoDb中的猫鼬子查询文档

网站源码admin20浏览0评论

使用mongoDb中的猫鼬子查询文档

使用mongoDb中的猫鼬子查询文档

我有2个模式:

const shop = new mongoose.Schema({
id:String,
name:{type: String , required:true},
address:String,

reviews: [reviewSchema]
});

const reviewSchema = new mongoose.Schema({
    author: String,
    rating: {type: Number, required: true, min: 0, max: 5},
    reviewText: String,
    createdOn: {type: Date, "default": Date.now}

});

使用猫鼬,我想使用特定商店中的评论ID查询特定评论。我的api将是这样的:http://localhost:3000/api/locations/:shopId/reviews/:reviewId我查看了文档,但它正在使用其他路径(例如作者),但不使用id。

回答如下:

使用mongodb聚合框架将很容易。

使用$match,我们将找到具有给定_id的商店,使用$filter,我们将使用给定的reviewId过滤评论。

const Shop = require("../models/shop"); //change this to match your app
const mongoose = require("mongoose");
const ObjectId = mongoose.Types.ObjectId;

router.get("/locations/:shopId/reviews/:reviewId", async (req, res) => {
  const { shopId, reviewId } = req.params;

  const result = await Shop.aggregate([
    {
      $match: {
        _id: ObjectId(shopId), //if you meant to filter by id, replace with id: shopId
      },
    },
    {
      $addFields: {
        reviews: {
          $filter: {
            input: "$reviews",
            as: "review",
            cond: { $eq: ["$$review._id", ObjectId(reviewId)] },
          },
        },
      },
    },
  ]);
  res.send(result);
});

假设您的这家商店有3条评论:

{
    "_id": "5ebafc8c03aee03284268239",
    "id": "id1",
    "name": "Shop 1",
    "reviews": [
        {
            "_id": "5ebafc8c03aee0328426823c",
            "rating": 3,
            "reviewText": "I gave 3",
            "createdOn": "2020-05-12T19:44:12.430Z"
        },
        {
            "_id": "5ebafc8c03aee0328426823b",
            "rating": 4,
            "reviewText": "I gave 4",
            "createdOn": "2020-05-12T19:44:12.430Z"
        },
        {
            "_id": "5ebafc8c03aee0328426823a",
            "rating": 5,
            "reviewText": "I gave 5",
            "createdOn": "2020-05-12T19:44:12.429Z"
        }
    ]
}

您想用"_id": "5ebafc8c03aee0328426823b"查找评论。当您向http://localhost:3000/api/locations/5ebafc8c03aee03284268239/reviews/5ebafc8c03aee0328426823b]发送获取请求时>

结果将是:

[
    {
        "_id": "5ebafc8c03aee03284268239",
        "id": "id1",
        "name": "Shop 1",
        "reviews": [
            {
                "_id": "5ebafc8c03aee0328426823b",
                "rating": 4,
                "reviewText": "I gave 4",
                "createdOn": "2020-05-12T19:44:12.430Z"
            }
        ],
        "__v": 0
    }
]

注意,由于未提供预期的输出,因此可能需要稍微改变结果的形状。

Mongo playground

发布评论

评论列表(0)

  1. 暂无评论