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

编程入门 行业动态 更新时间:2024-10-07 06:48:32

使用mongoDb中的猫鼬子查询<a href=https://www.elefans.com/category/jswz/34/1770955.html style=文档"/>

使用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

更多推荐

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

本文发布于:2024-05-07 12:43:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756293.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   mongoDb   猫鼬子

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!