代码之家  ›  专栏  ›  技术社区  ›  john doe

基于子文档的Mongoose过滤器MongoDB

  •  -1
  • john doe  · 技术社区  · 6 年前

    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 回复  |  直到 6 年前
        1
  •  1
  •   mickl    6 年前

    你不能明确地提到 length $type "array" $size $not 0

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