【问题标题】:How to have referenced document inside collection with conditions如何在有条件的集合中引用文档
【发布时间】:2017-03-11 13:02:48
【问题描述】:

我的架构如下:

foodtruck.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Items = require('./items.js');


var FoodTruckSchema = new Schema({
    foodtruck_name:String,
    foodtruck_location:String,
    foodtruck_rating:{type:Number,default:5},
    foodtruck_total_votes:{type:Number,default:0},
    foodtruck_tag:String,
    foodtruck_timing:String,
    foodtruck_cusine:String,
    foodtruck_img:String,
    foodtruck_logo:String,
    item_list: [ {type : mongoose.Schema.ObjectId, ref : 'items'}]
},{ versionKey: false });



module.exports = mongoose.model('foodtruck',FoodTruckSchema);

items.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ItemSchema = new Schema({
    no_of_times_ordered:Number,
    item_name:String,
    item_tag:String,
    item_category:String,
    item_illustrations:[String],
    item_stock:Number,   //0 available 1 last 5 items 2 not available
    item_quantity_ordered:{type:Number,default:0},
    item_price:Number,
    item_img:String,
    no_of_likes:{type:Number,default:0}
},{ versionKey: false });

module.exports = mongoose.model('items',ItemSchema);

现在,我想要有这样一个 itemlist 的 foodtruck,里面的所有项目都应该有 no_of_times_ordered 大于 4000。为此,我提出如下查询:

 foodtr.find({
        'item_list.no_of_times_ordered': {
            $gt: 4000
        }
    }, function(err, items) {
        if (err) res.json({
            status: '404',
            message: 'there is no data available'
        });
        res.json({
            status: '200',
            message: 'popular items list',
            data: items
        });
    });
};

但是在这里,我得到了一个空列表,那么我怎样才能根据上面所说的要求获得项目列表呢?

【问题讨论】:

    标签: mongoose mongoose-schema


    【解决方案1】:

    您查询错误,您不能将item_list.no_of_times_ordered 用于引用文档。您需要为此使用populate,并且仅对于选择性项目,使用match 到query populate 中的条件。

    试试这个:

    foodtr.find({}).populate({
        path : 'item_list',
        match : {no_of_times_ordered : { $gt :4000}}
    }).exec(function(err, items) {
        ...
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 2014-08-16
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 2018-05-27
      相关资源
      最近更新 更多