猫鼬填充了 2 个文件和 2 个集合 return 空数组

Mongoose populate with 2 Files and 2 Collections return empty array

我的问题是我填充查询 returns 一个空数组。我知道无数的帖子,但是 none 为我提供了新的见解。

我的第一个架构: 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);
        });

使用 Postman 获取站点,显示 Tripcount: []。知道我做错了什么吗?

你能试试下面的方法吗?将一个空对象传递给您的查找方法。

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);
        });

我想我会根据之前的评论添加另一个答案。看来您的数据没有链接起来。 Mongoose populate 将获取 Station 的 Tripcount 数组中的值,并尝试使用 _id 字段在 Tripcount 集合中查找 Tripcount 对象,假设您有以下车站

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

在您的 Tripcount Collection 中,您需要以下内容才能与上面的车站相匹配

[
  {
    _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
    },
  ]
}