【问题标题】:Mongoose not populating array in MongodbMongoose 没有在 Mongodb 中填充数组
【发布时间】:2019-11-24 07:05:48
【问题描述】:

这是我的游戏架构:

var mongoose = require('mongoose');

const GameSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },

    publishers: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Publisher'
        }
    ]
});

var GameModel = mongoose.model('Game', GameSchema);
module.exports = GameModel;

这是我的发布者架构:

var mongoose = require('mongoose');

const PublisherSchema = new mongoose.Schema({
    companyName: {
        type: String,
        required: true
    },

    firstParty: {
        type: Boolean,
        required: true
    },

    website: {
        website: String,
    }
});

var PublisherModel = mongoose.model('Publisher', PublisherSchema);

module.exports = PublisherModel;

我有一张你可以在我的 mongoDB 中的“游戏”集合中找到的图片:

当我使用这条路线时:

router.get('/games', async function(req, res) {

    const games = await Game
        .find()
        .populate('publishers')
        .select('title publishers')

        res.json(games);
})

我有空数组作为发布者的结果。如果我不在 Schema 中使用数组,则该数组已正确填充,并且我将发布者的数据放入每个游戏中。那么为什么 mongoose 是数组时不填充呢?

【问题讨论】:

  • Mongoose 可以填充数组。可能原因是.select()。尝试删除它,看看填充是否有效。
  • 我试过了,结果是一样的,我得到了一个空数组。如果我删除数组并将架构更改为具有唯一值,并让此代码完全相同,则填充有效。所以它是一个数组的事实就是问题所在。

标签: node.js mongodb api mongoose


【解决方案1】:

通过如下修改架构定义来检查以下内容

我认为以下可以解决您的问题,请尝试通过重新定义以下发布者来尝试

Publishers: [
        publisher: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Publisher'
       }
   ]

【讨论】:

    【解决方案2】:

    我认为schema的定义更多的是定义我们想要处理的对象的结构,而不是我们想要处理的对象的数量。

    据我所知,Schema 定义是定义模型的语义并利用中间件功能。

    可以保存多个满足相同语义定义的对象,但定义本身不能是数组

    谢谢 帕万

    【讨论】:

    • 那么我怎么会有很多游戏发行商呢?那么更新时的 $push 呢?
    猜你喜欢
    • 2019-07-28
    • 2019-06-25
    • 2021-07-09
    • 2019-03-28
    • 2019-01-31
    • 2016-02-14
    • 2014-12-05
    • 2014-11-09
    相关资源
    最近更新 更多