2017-05-03 97 views
0

我有我的填充查询返回一个空数组的问题。我意识到无数的帖子,但是他们没有一个为我提供新的见解。猫鼬填充2文件和2集合返回空阵列

我的第一个模式: station.js

var stationSchema = new Schema({ 
    _id: Number, 
    Tripcount: [{ type: Number, ref: 'Tripcount'}] 
}, 
    {collection: 'stations'} 
); 
module.exports = mongoose.model('Station', stationSchema); 

我的第二个:trips.js

var tripSchema = new Schema({ 
    _id: Number, 
    Tripcount: Number 
}, 
    {collection: 'trips'} 
); 
module.exports = mongoose.model('Tripcount', tripSchema); 

而且我的查询是这样的,根据大多数的答案这应该做的工作:

var Station = require('./station.js'); 
var query = Station.find() 
     .populate({ 
      path: 'Tripcount', 
      model : 'Tripcount' 
     }); 
     query.exec(function(err, stations){ 
      if(err) 
       res.send(err); 
      res.json(stations); 
     }); 

使用邮递员获取站,它显示Tripcount: []。任何想法我做错了什么?

回答

1

我想我会根据以前的评论添加另一个答案。看起来你的数据没有连接起来。猫鼬填入将在车站的Tripcount数组中的值,并尝试使用_id字段,因此可以说你有以下站

{ 
    _id: 1, 
    Tripcount: [100, 101, 102] 
} 

在你Tripcount收集查找的Tripcount对象Tripcount集合中,你将需要以下至与车站匹配以上

[ 
    { 
    _id: 100, 
    Tripcount: 2 
    }, 
    { 
    _id: 101, 
    Tripcount: 4 
    }, 
    { 
    _id: 102, 
    Tripcount: 6 
    }, 
] 

然后,当你运行你的查询,你会得到以下

{ 
    _id: 1, 
    Tripcount: [ 
    { 
     _id: 100, 
     Tripcount: 2 
    }, 
    { 
     _id: 101, 
     Tripcount: 4 
    }, 
    { 
     _id: 102, 
     Tripcount: 6 
    }, 
    ] 
} 
+0

谢谢,但在收藏中没有tripcount数组,可能我没有说清楚。它应该使用来自station collection的_id来匹配tripcount集合中的_id。我想我必须使用findById。 – ffritz

+0

那么你的参考必须是来自Tripcount系列的Station,你必须转置你的查询 – RedJandal

+0

就像Trip.find()。 – ffritz

0

您可以尝试以下操作。将空对象传递给查找方法。

var Station = require('./station.js'); 
var query = Station.find({}) 
     .populate({ 
      path: 'Tripcount', 
      model : 'Tripcount' 
     }); 
     query.exec(function(err, stations){ 
      if(err) 
       res.send(err); 
      res.json(stations); 
     }); 
+0

想这已经,没有任何变化。 – ffritz

+0

你确定你的数据库中有数据? – RedJandal

+0

是的,我也用mongo-express,所以我可以看到我在做什么。我也检查只提取Tripdurations,所以只改变查询,这是行不通的。它正在填充什么不起作用。 – ffritz