【发布时间】:2018-05-03 20:21:43
【问题描述】:
我在这里看到了一些与此类似的问题,但似乎没有一个解决方案有效。我正在为我的婚礼创建一个餐桌规划器,并且我正在尝试执行查询以返回所有餐桌(顶级餐桌、第一桌、第二桌等)以及分配给这些餐桌的客人列表。我有以下架构:
const guestSchema = new mongoose.Schema({
firstname: {
type: String,
required: 'Please provide the first name of the guest',
trim: true
},
surname: {
type: String,
required: 'Please provide the surname of the guest',
trim: true
},
attending: {
type: String,
default: 'Awaiting RSVP'
},
menu: {
type: String,
default: 'Awaiting RSVP'
},
allergies: {
type: String,
default: 'Awaiting RSVP'
},
table: [{
type: mongoose.Schema.ObjectId,
ref: 'Table',
}]
});
const tableSchema = new mongoose.Schema({
name: {
type: String,
required: 'Please provide the name of the table',
trim: true
},
capacity: {
type: Number,
required: 'Please provide the capacity of the table',
},
guests: [{
type: mongoose.Schema.ObjectId,
ref: 'Guest',
}]
});
在我的 guestController.js 中,我设置了一个 API 端点,如下所示:
exports.getTableGuests = async (req, res) => {
const guests = await Table.find().populate({path: 'guests', select: 'firstname surname', model: 'Guest'});
res.json(guests);
};
这里的客人是表模型中的外部字段的名称。在返回的 JSON 中,我确实得到了一个 guest 数组,但它是空的。
有什么想法吗?
【问题讨论】:
-
嗨詹姆斯豪厄尔;您能否粘贴数据库中的表格和客人记录示例,以确认您正在查询的数据类型?
-
当然我已经从 MongoDB Compass 添加了屏幕截图
-
实际上,屏幕截图并不理想。对他们的建议是图片在帖子中很有用,但确保帖子在没有它们的情况下仍然清晰。因此,与其显示数据的屏幕截图,不如直接将实际的 json 复制并粘贴到问题中。 cfmeta.stackoverflow.com/questions/303812/…
-
好酷很快就会上传数据。刚刚发现问题的可能原因,所以我先尝试修复。