【发布时间】: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