我刚开始学习express和MongoDB。我最近遇到了这样的问题,我试图选择rooy
模型中的所有子文档。
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);
您可以通过两种方式从房间
集合中仅选择预订
字段。
>
使用select
方法
const books = await Room.find().select('bookings').populate('bookings');
将投影对象传递给.find()
方法
const books = await Room.find({}, { bookings: 1 }).populate('bookings');
有关详细信息,请参阅:
p.s:您正在将集合的名称(book
)传递给.populate()
方法,而应该传递要填充的字段的名称,在您的示例中是bookings
。
更改
.populate('book');
至
.populate('bookings');