MongoDB使用基于子文档的Mongoose筛选器

时间:2018-07-02 18:52:49

标签: mongodb mongoose

我在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)
})

我想念什么?

1 个答案:

答案 0 :(得分:1)

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

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