【问题标题】:MongoDB Using Mongoose Filter Based on SubDocumentsMongoDB 使用基于子文档的 Mongoose 过滤器
【发布时间】:2018-07-03 03:19:36
【问题描述】:

我在 Dish 和 Review 之间建立了一对多的关系。一道菜可以有很多评论。这是用于菜肴和评论的猫鼬模式:

const mongoose = require('mongoose')
const Review = require('./reviewSchema')

// defining the structore of your document
let dishSchema = mongoose.Schema({
  name : String,
  price :Number,
  imageURL :String,
  reviews : [Review.schema]
})

// convert the schema into a model class which you can use in your code
const Dish = mongoose.model('Dish',dishSchema)

module.exports = Dish


const mongoose = require('mongoose')

let reviewSchema = mongoose.Schema({
  title : String,
  description :String
})

const Review = mongoose.model('Review',reviewSchema)

module.exports = Review 

我遇到的问题是,如果它们至少有一条评论,我想获取所有菜肴。这是我编写的代码,它返回一个空数组。

Dish.find({
  "reviews.length" : { $gt : 0 }
},function(error,dishes){
  console.log(dishes)
})

我错过了什么?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您不能显式引用数组的length 属性。要检查数组是否不为空,您可以检查它是否为 $type "array" 以及其 $size 是否为 $not 0

    Dish.find({ reviews: { $type: "array", $not: { $size: 0 } } },
        function(error,dishes){
          console.log(dishes)
    })
    

    【讨论】:

      猜你喜欢
      • 2017-10-01
      • 2019-07-13
      • 2018-01-26
      • 2020-12-29
      • 2015-05-25
      • 1970-01-01
      • 2018-09-29
      • 2021-05-06
      相关资源
      最近更新 更多