【问题标题】:Mongoose populate with 2 Files and 2 Collections return empty arrayMongoose 填充 2 个文件和 2 个集合返回空数组
【发布时间】:2023-04-09 11:08:01
【问题描述】:

我的填充查询返回一个空数组的问题。我知道无数的帖子,但没有一个为我提供新的见解。

我的第一个架构: 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: []。任何想法我做错了什么?

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

    你可以试试下面的。将一个空对象传递给您的 find 方法。

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

    【讨论】:

    • 你确定你的数据库中有数据吗?
    • 是的,我也在使用 mongo-express,所以我可以看到我在做什么。我还检查了只获取 Tripdurations,所以只更改查询,这确实有效。它正在填充不起作用的东西。
    • 如果删除查询的填充部分会怎样?
    • 根据站点模式返回站点数据。 tripduration 在另一个集合中。
    • 您能否确认车站的 Tripcount 值与 Tripcount 集合中的 id 匹配?
    【解决方案2】:

    我想我会根据以前的 cmets 添加另一个答案。您的数据似乎没有链接起来。 Mongoose 填充将获取 Station 的 Tripcount 数组中的值,并尝试使用 _id 字段在 Tripcount 集合中查找 Tripcount 对象,因此假设您有以下站点

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

    在您的 Tripcount Collection 中,您需要以下内容才能与 Station Above 相匹配

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

    【讨论】:

    • 谢谢,但是车站集合中没有tripcount数组,可能我没有说清楚。它应该使用 station 集合中的 _id 来匹配 tripcount 集合中的 _id。我想我必须使用 findById。
    • 那么您的参考必须是 Tripcount 集合中的 Station,并且您必须转置您的查询
    • 那么像 Trip.find().populate with the station?
    • 是的,或者看看 $lookup mongodb 文档docs.mongodb.com/v3.2/reference/operator/aggregation/lookup
    • 非常感谢,帮了大忙!
    猜你喜欢
    • 2022-12-09
    • 2016-12-04
    • 1970-01-01
    • 2016-06-04
    • 2021-01-02
    • 2019-09-17
    • 1970-01-01
    • 2023-01-15
    • 2020-05-27
    相关资源
    最近更新 更多