node.js - 填充返回整个父文档
问题描述
我刚开始学习express和mongodb。我最近遇到了这种问题,我正在尝试选择Room
模型内部的所有子文档。
const books = await Room.find().populate('book');
但是当我只想选择bookings
字段时,它会返回整个房间文档。
这是本书的架构
const bookSchema = new mongoose.Schema({
startDate: {
type: Date,
required: true,
},
endDate: {
type: Date,
required: true,
},
name: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
});
module.exports = mongoose.model("book", bookSchema)
这是房间模式
const roomSchema = new mongoose.Schema({
currentlyReserved: {
type: Boolean,
default: false,
},
people: {
type: Number,
required: true,
},
roomNumber: {
type: Number,
required: true,
},
pricePerPerson: {
type: Number,
required: true,
},
reservedUntil: {
type: Date,
default: null,
},
reservedBy: {
type: String,
default: null,
},
bookings: {
type: [{ type: mongoose.Schema.Types.ObjectId, ref: "book" }],
},
});
module.exports = mongoose.model("room", roomSchema);
解决方案
您可以使用第二个 arg 投影到 find()。
https://docs.mongodb.com/manual/reference/method/db.collection.find/#projection
const books = await Room.find({}, {bookings: 1}).populate('bookings');
推荐阅读
- javascript - 让VS代码在调试js代码时默认选择Node.js环境
- c++ - 在 intel 内部函数 (AVX) 中使用混合指令
- sql - 将 varchar 转换为日期 ddmmyyyy 时出错
- azure - Azure VM 无法访问端口 8080
- ios - Kingfisher + RxSwift DownsamplingImageProcessor 图像失败
- python-3.x - 从python中的元素列表中获取属性
- kubernetes - 使用 sh 命令时 Kubernetes Pod 的容器未运行
- flutter - 如何创建自定义颤振 sdk 小部件,重建颤振和使用新的小部件
- python - 在不同列上解析 JSON 的结果
- javascript - 我只需要在开始日期选择的日期选择器中显示未来一个月的日期