首页 > 解决方案 > 填充返回整个父文档

问题描述

我刚开始学习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);

标签: node.jsmongodbexpressmongoose

解决方案


您可以使用第二个 arg 投影到 find()。

https://docs.mongodb.com/manual/reference/method/db.collection.find/#projection

const books = await Room.find({}, {bookings: 1}).populate('bookings');

推荐阅读