MongoDB使用基于子文档的Mongoose过滤器

问题描述 投票:-1回答:1

我和Dish之间有一对多的关系。一道菜可以有很多评论。以下是菜单和评论的Mongoose Schema:

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个回答
1
投票

您无法显式引用数组的length属性。要检查数组是否为空,您可以检查它是否为$type "array",如果它的$size$not 0

Dish.find({ reviews: { $type: "array", $not: { $size: 0 } } },
    function(error,dishes){
      console.log(dishes)
})
© www.soinside.com 2019 - 2024. All rights reserved.