【问题标题】:Find documents by object field inside array按数组内的对象字段查找文档
【发布时间】:2018-02-10 06:22:10
【问题描述】:

我需要一个演出模式,并且我只想获得演出中的可用门票。我需要找到所有availableTickets > 0 的文档,并且只获取带有show._id 和show.title 的子文档。我该怎么办?

// Show's Model

const mongoose = require('../../database/mongoose')

const ShowSchema = mongoose.Schema({
    title: { type: String, required: true },
    description: { type: String, required: true },
    startsAt: { type: Date, required: true },
    endsAt: { type: Date, required: true },
    openToBuyAt: { type: Date, required: true },
    closedToBuyAt: { type: Date, required:true },
    status: { type: Boolean, required: true },
    sectors: [{
        name: { type: String, required: true },
        price: { type: Number, required: true },
        availableTickets: { type: Number, required: true }
    }],
    convenienceFee: { type: Number, required: true },
    images: [
        { type: String }
    ]
})

module.exports = mongoose.model('Show', ShowSchema)

预期结果

{
    "status": "success",
    "tickets": [
        {
            "show._id": "ddadadas12a",
            "show.title": "Crazy Show",
            "sectors": [
                {
                    "name": "VIP"
                    "price": 50.25,
                    "availableTickets": 12
                },
                {
                    "name": "General Sector"
                    "price": 20.00,
                    "availableTickets": 5
                }
            ]
        }
    ]
} 

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongodb-query


    【解决方案1】:

    很遗憾,您的架构有误。

    您没有“可用门票”字段。如果您有任何字段,例如 availableTickets

    你可以像这样简单地做到这一点:

    这个查询有两个主要部分:

    1. 条件
    2. 项目字段:0/1

    ShowSchema.find({availableTickets : { $gt: 0 }}, { title: 1, description: 0, startsAt: 0, endsAt: 0, openToBuyAt: 0, closedToBuyAt: 0, status: 0, sectors:1, convenienceFee:0, images:0, })

    【讨论】:

      猜你喜欢
      • 2015-04-24
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-12
      • 1970-01-01
      • 2016-04-23
      • 2014-09-25
      相关资源
      最近更新 更多